从另一个活动更改一个活动的背景

2024-01-04

示例 我有 3 个活动:活动 1、活动 2 和活动 3。 Activity1 包含一个按钮,单击该按钮可以更改 Activity2 和 Activity3 的背景。这可能吗?如果是的话怎么办?我对使用该方法有一个想法:

//example for activity1

public void onClick(View v) {
View background = findViewById(R.id.activity1relativeLayout);
background.setBackgroundResource(R.drawable.customBackground);

}

可以用于单个活动。使用单个按钮操作多个活动怎么样?


您可以将颜色保存在SharedPreferences当您单击按钮时。然后在变色活动中onStart阅读首选项并更改背景颜色。

Button.onClick(...)

SharedPreferences sharedPref = context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("background_resource", selected_background);
editor.apply();

Activity.onStart(...)

SharedPreferences sharedPref = context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
int bg = sharedPref.getInt("background_resource", android.R.color.white); // the second parameter will be fallback if the preference is not found
getWindow().setBackgroundDrawableResource(bg);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从另一个活动更改一个活动的背景 的相关文章

随机推荐