在另一个活动中使用微调器更改文本视图的颜色



>我有两个活动活动 活动 1 和活动 2。 在活动 2 中,我有一个由几种颜色填充的微调器,我想做的是当我在微调器中选择一种颜色时,它会更改活动 1 内文本视图的颜色当我在同一个活动中执行此操作时,它会起作用,否则没有任何帮助将不胜感激。

在"设置"中使用这样的共享首选项

//create SharedPreferences
SharedPreferences sharedPreferences = this.getSharedPreferences("nameYourSharedPref", Context.MODE_PRIVATE);
//get what color is selected from spinner and add it to SharedPreferences as a String for example
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("color", "red");
editor.apply();

在您的"主活动"中获取这样的颜色

//create SharedPreferences
SharedPreferences sharedPreferences = this.getSharedPreferences("nameYourSharedPref", Context.MODE_PRIVATE);
//this will return the color you saved before or "defaultValue"...
String userSelectedColor = sharedPreferences.getString("color", "defaultValue");
//code to change the color wherever you want
if(userSelectedColor.equals("defaultValue"))
{
//don't change anything
}
else if(userSelectedColor.equals("red"))
{
//change color to red
}

在 Activity1 中使用此意图方法

Intent i=new Intent(Edit_News.this,Activity.class);
startActivityForResult(i,2);

**在活动 2 中 **

在微调器中选择颜色,并在选择颜色后使用它,并在此传递您的颜色代码

Intent intent = new Intent();
intent.putExtra("color",#fffff);
setResult(Activity.RESULT_OK, intent);
finish();

现在在您的活动 1 中,当活动 2 完成时,此方法将调用

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
super.onActivityResult(requestCode, resultCode, result);
switch (requestCode) {
case 2:
if (resultCode == RESULT_OK)
{
Bundle bundle = result.getExtras();
int    colorcod= bundle.getDouble("color");
mTextView.setTextColor(Color.parseColor(colorcod));
}
break;
}
}

最新更新