我的应用程序有三种难度模式;简单、中等和困难。我有一个变量来跟踪难度 (0-2)。如何使用此变量来更改应用程序的背景颜色?例如,当模式为简单时,我希望背景为绿色,黄色为中等,红色为困难。
这是我的布局。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/myBackground" >
</RelativeLayout>
我有字符串资源:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="myBackground">#01CC18</color>
</resources>
但是,我想要做的是能够在程序本身而不是 xml 布局中更改背景。这可以吗?
最佳答案
使用 LinearLayout 填充主视图。然后获取此布局的句柄:
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
每当难度发生变化时,您都可以使用此句柄来更新背景颜色:
switch(difficulty) {
case 0:
layout.setBackgroundColor(android.R.color.green);
break;
case 1:
layout.setBackgroundColor(android.R.color.orange);
break;
case 2:
layout.setBackgroundColor(android.R.color.red);
break;
default:
break;
}
关于java - 如何根据用户输入更改 Android 应用程序的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9072523/