如何通过Settings Activity的按钮修改Main Activity的背景颜色
问题原因
- 在Settings页面调用
findViewById(R.id.mainLayout)只能获取当前页面布局内的控件,mainLayout属于Main页面布局,在Settings中获取到的实例为null,修改操作自然不生效 - 直接通过
startActivity启动的Main是全新实例,跳转后修改非当前页面控件没有任何作用
可用解决方案
方案1:通过Activity Result API回传参数(适用于从Main跳转进入Settings,修改后返回Main的场景,官方推荐用法)
- 调整Main页面代码,注册结果接收器处理回传的颜色值
public class Main extends AppCompatActivity { private RelativeLayout mainLayout; // 注册页面返回结果接收器 private final ActivityResultLauncher<Intent> settingsLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == RESULT_OK && result.getData() != null) { int targetColor = result.getData().getIntExtra("bg_color", Color.WHITE); mainLayout.setBackgroundColor(targetColor); } } ); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainLayout = findViewById(R.id.mainLayout); // 原跳转Settings的按钮点击事件修改为以下逻辑 Button toSettingsBtn = findViewById(R.id.to_settings_btn); toSettingsBtn.setOnClickListener(view -> { Intent intent = new Intent(Main.this, Settings.class); settingsLauncher.launch(intent); }); } }
- 调整Settings页面代码,选中颜色后回传结果并关闭当前页面
public class Settings extends AppCompatActivity { private Button changeColorButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); changeColorButton = findViewById(R.id.changeColorButton); changeColorButton.setOnClickListener(view -> { Intent resultIntent = new Intent(); // 存入要设置的背景色值 resultIntent.putExtra("bg_color", Color.BLUE); setResult(RESULT_OK, resultIntent); // 关闭Settings回到上层Main页面 finish(); }); } }
方案2:通过SharedPreferences持久化存储配置(适用于需要重启APP后仍保留设置的场景)
- 修改Settings页面点击事件,存储颜色配置:
changeColorButton.setOnClickListener(view -> { getSharedPreferences("app_config", MODE_PRIVATE) .edit() .putInt("bg_color", Color.BLUE) .apply(); finish(); });
- 在Main页面的
onResume生命周期中读取配置更新背景:
@Override protected void onResume() { super.onResume(); int savedColor = getSharedPreferences("app_config", MODE_PRIVATE) .getInt("bg_color", Color.WHITE); mainLayout.setBackgroundColor(savedColor); }
内容的提问来源于stack exchange,提问作者Rui Fernando
相关产品推荐
相关产品推荐

