如何根据用户输入更改我的Android应用程序的背景颜色?

时间:2012-01-30 23:51:55

标签: java android colors background background-color

我的应用程序有三种难度模式;简单,中等,难度。我有一个跟踪难度的变量(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布局中。可以这样做吗?

2 个答案:

答案 0 :(得分:4)

使用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;
}

答案 1 :(得分:0)