[英]Changing background color of all activities
我有一个“设置”活动,其中显示5种不同的颜色选项,可将应用程序的背景或文本或按钮颜色更改为该颜色。
我现在只关注背景变化。 通过阅读,我可以使用SharedPreferences做类似的事情:
现在在我的Settings类中,每个颜色选项都有以下代码:
ImageButton changeBgRed = (ImageButton) findViewById(R.id.bgRed);
changeBgRed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("background", Color.RED);
editor.commit();
}
});
令我困惑的是如何编码我的其他类,以便它们从SharedPreference中读取颜色并更改背景。
对于我的HomeScreen类,我有以下代码/想法(我想代码大部分都可以复制/粘贴到其他活动中):
@Override
protected void onResume(){
super.onResume();
background = (RelativeLayout) findViewById(R.id.rootLayout);
SharedPreferences settings = getSharedPreferences("Background", Context.MODE_PRIVATE);
if(settings.getInt("background", Color.RED) == Color.RED)
background.setBackgroundColor(Color.RED);
else
background.setBackgroundColor(Color.WHITE);
我认为其他颜色的包装会更多。 但是现在,这不起作用。 当我运行该应用程序时,主屏幕的背景开始显示为红色。
我不是很了解SharedPreferences的工作原理吗? 请指引我正确的方向。
如活动文档中所述 ,来自Activity
类的getPreferences()
方法:
检索SharedPreferences对象,以访问此活动专用的首选项。 通过传入此活动的类名称作为首选项名称,可以简单地调用基础的getSharedPreferences(String,int)方法。
因此,您实际上仅在设置“活动”中设置颜色,而不能从其他“活动”中访问该值。
要解决此问题,您可以在Settings类中尝试以下代码:
ImageButton changeBgRed = (ImageButton) findViewById(R.id.bgRed);
changeBgRed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
// Changed the line below to get the same preferences used in Home Screen
SharedPreferences prefs = getSharedPreferences("Background", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("background", Color.RED);
editor.commit();
}
});
考虑到您希望将白色背景作为默认设置,这将是您的主屏幕代码,并且通过单击“设置”屏幕上的changeBgRed
视图,它将使您的主屏幕背景变为红色。 请记住,无论何时要返回默认状态(白色背景),请先卸载应用程序并重新安装。
@Override
protected void onResume(){
super.onResume();
background = (RelativeLayout) findViewById(R.id.rootLayout);
SharedPreferences settings = getSharedPreferences("Background", Context.MODE_PRIVATE);
if(settings.getInt("background", Color.WHITE) == Color.RED)
background.setBackgroundColor(Color.RED);
else
background.setBackgroundColor(Color.WHITE);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.