在Android中更改布局的背景颜色

13
我有一个简单的Android应用程序,有3个按钮。当我点击第一个按钮时,我想要更改布局的背景颜色(现在是白色...我想在按下按钮时更改为其他颜色)。我该如何做到这一点? 在那个按钮上,我有一个myClickHndler事件。
    public void myClickHandler(View view) {
    switch (view.getId()) {
    case R.id.Button01:
        text.setText("Button 1 was clicked");
        break;
    case R.id.Button03:
        //text.setText("Button 3 was clicked");
                    .................... // ?
        break;
    }
}

谢谢!


抱歉,当我点击第三个按钮时,我想改变颜色,而不是在第一个按钮上。谢谢! - qwerty
4个回答

27

给你的 LinearLayout 分配一个 Id,像这样:

<LinearLayout android:id="@+id/laidout"
        ...>

然后从你的Java类中调用:

...
case R.id.Button03:
//text.setText("Button 3 was clicked");
  .................... // ?
mlayout= findViewById(R.id.laidout);
// set the color 
mlayout.setBackgroundColor(Color.WHATEVER);
// you can use setBackgroundResource() and pass appropriate ID
// if you want a drawable bundled as resource in the background
mlayout.setBackgroundResource(R.drawable.background_img);
break;
...

[编辑]: 添加了在评论中请求的代码


好的,谢谢!如果我想用一个.png图像来更改布局的背景,我该怎么做?这有可能吗?我在res/drawable文件夹中有一个png图像,并且我想将它显示为布局的背景。 谢谢! - qwerty
是的,你可以这样做。我已经在我的帖子中添加了代码,请查看。 - Samuh
在某些情况下,这似乎无法正常工作。在onCreate或onResume中调用findViewById(R.id.laidout)时会抛出RuntimeException(不确定其他地方)。 - user153275

3
如果您想动态更改背景,请使用:
 YourView.setBackgroundColor(Color.argb(255, 255, 255, 255));

1

setBackgroundDrawable已被弃用

尝试以下简单代码...

有效代码:

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.mainLayout);
linearLayout.setBackgroundResource(R.drawable.backrepeat_blue);

享受


0
尝试以下代码...
代码:
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.newImage); 
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.GameLayout);
linearLayout.setBackgroundDrawable(drawable);

希望这能有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接