繁体   English   中英

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

[英]How can I change the background color of my MainActivity from a second activity using colored buttons as user choices?

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

在 MainActivity 我有一个 Intent 将我切换到第三个活动。

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();
    }
  };

回到 MainActivity 我有一个 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_REQUEST是您为startActivityForResult设置的int ,而COLOR_CODE是捆绑键的任何String

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM