这是我更改背景的代码
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.theme1:
mainLayout.setBackgroundResource(R.drawable.blackgreygradientbackground);
if (selectedBackgroundId == R.id.theme1){
Toast.makeText(getApplicationContext(), "Background already set", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Background set", Toast.LENGTH_SHORT).show();
}
selectedBackgroundId = R.id.theme1;
return true;
case R.id.theme2:
mainLayout.setBackgroundResource(R.drawable.redpinkgradientbackground);
if (selectedBackgroundId == R.id.theme2){
Toast.makeText(getApplicationContext(), "Background already set", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Background set", Toast.LENGTH_SHORT).show();
}
selectedBackgroundId = R.id.theme2;
return true;
}
}
在我的主要活动中,用户可以通过单击菜单更改工具栏中的背景,它确实会更改背景,但问题是如何在所有活动中更改它并在用户关闭应用程序并重新启动时保存它它?
所以我的问题是:
现在它只会改变主要活动的背景,但我希望实现这是我所有活动的变化。
如何在重启时保存拾取的背景?
我使用自己的图像作为背景,只能找到带颜色的教程。
提前致谢,
文斯
修改
int theme1 = R.drawable.blackgreygradientbackground;
int theme2 = R.drawable.redpinkgradientbackground;
int mSelectedBackground;
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.theme1:
mainLayout.setBackgroundResource(theme1);
mSelectedBackground = theme1;
mEditor = mSharedPreferences.edit();
mEditor.putInt("mSelectedBackground", mSelectedBackground);
mEditor.apply();
if (selectedBackgroundId == R.id.theme1){
Toast.makeText(getApplicationContext(), "Background already set", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Background set", Toast.LENGTH_SHORT).show();
}
selectedBackgroundId = R.id.theme1;
return true;
case R.id.theme2:
mainLayout.setBackgroundResource(theme2);
mSelectedBackground = theme2;
mEditor = mSharedPreferences.edit();
mEditor.putInt("mSelectedBackground", mSelectedBackground);
mEditor.apply();
if (selectedBackgroundId == R.id.theme2){
Toast.makeText(getApplicationContext(), "Background already set", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Background set", Toast.LENGTH_SHORT).show();
}
selectedBackgroundId = R.id.theme2;
return true;
}
}
所以我不确定我是否正确行事,我按照文档进行操作,但我现在如何将我的活动的主要布局设置为用户在所有活动中选择的背景并保存?
谢谢,
答案 0 :(得分:0)
您可以将所选背景保存在持久存储中(如SharedPreferences)
在每个活动的onCreate上,您可以通过从保存SharedPreferences获取来设置它
示例可以在这里找到: https://developer.android.com/training/data-storage/shared-preferences.html