如何使用彩色按钮作为用户选择从第二个活动更改主活动的背景颜色?



我有一个包含多个活动的程序。从我的主活动中,我可以单击一个按钮,该按钮会将用户发送到ThirdActivity_ColorPicker。在第三个活动中,我有三个按钮,名为颜色,单击时应该更改 MainActivity 的背景颜色。除了,它不会改变背景颜色。

在主活动中,我有一个意图,可以将我切换到第三个活动。

private View.OnClickListener changeToColorPickerActivity = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent goToThirdActivityColorPicker = new Intent(getApplication(), ThirdActivity_ColorPicker.class);
startActivityForResult(goToThirdActivityColorPicker, COLOR_PICKER_REQUEST);
}
};

在我的第三个活动中,我有三个按钮,红色、蓝色和绿色,单击它们时应将 MainActivity 背景颜色更改为所选颜色。

private View.OnClickListener changeMainActivityToBlue = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intentBlue = new Intent();
setResult(RESULT_CODE_BLUE, intentBlue);
finish();
}
};

回到主活动,我有一个onActivityResult来接收来自第三活动的数据

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
thirdAct = new ThirdActivity_ColorPicker();
if(requestCode == RESULT_OK && resultCode == thirdAct.RESULT_CODE_RED){
constraintLayout.findViewById(R.id.main_layout).setBackgroundColor(getColor(R.color.redBackground));
}else if(requestCode == RESULT_OK && resultCode == thirdAct.RESULT_CODE_GREEN){
constraintLayout.findViewById(R.id.main_layout).setBackgroundColor(getColor(R.color.greenBackground));
}else if(requestCode == RESULT_OK && resultCode == thirdAct.RESULT_CODE_BLUE){
constraintLayout.setBackgroundColor(getColor(R.color.blueBackground));
}
}

结果我希望背景颜色随着上面的代码而改变,但使用正确,因为我知道我在某处做错了什么。 谢谢。

在您的ThirdActivity_ColorPicker中,更改每个颜色按钮单击时的代码,即(红色,绿色,蓝色等(,如下所示。这将为上一个活动设置捆绑包数据和结果。

Intent intentRed = new Intent();
intentRed.putExtra(COLOR_CODE, 
getApplicationContext().getResources().getColor(R.color.redBackground));
setResult(Activity.RESULT_OK, intentRed);
finish();

然后,在您的MainActivity中,在onActivityResult中进行以下更改:

if (requestCode == COLOR_PICKER_REQUEST && resultCode == RESULT_OK) {
if (data != null && data.getExtras() != null) {
Bundle bundle = data.getExtras();
int colorBg = bundle.getInt(COLOR_CODE);
findViewById(R.id.mainBg).setBackgroundColor(colorBg);
}
}

COLOR_PICKER_REQUESTint,您为startActivityForResult设置了COLOR_CODE是捆绑密钥的任何String

最新更新