在 Android 中更改布局的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2895367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
change background color of the layout in Android
提问by qwerty
I have a simple Android application, with 3 buttons. When i click on the 1st button, i wanna change the background color of the layout (which is now white... i wanna change in other color, when i press the button). How can i do this?
我有一个简单的 Android 应用程序,有 3 个按钮。当我点击第一个按钮时,我想改变布局的背景颜色(现在是白色......我想改变其他颜色,当我按下按钮时)。我怎样才能做到这一点?
On that button, i have a myClickHndler event
在那个按钮上,我有一个 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;
}
}
Thanks!
谢谢!
回答by Samuh
Give an Id to your LinearLayout
like this:
给你一个LinearLayout
像这样的ID :
<LinearLayout android:id="@+id/laidout"
...>
and then from your java class say:
然后从你的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;
...
[EDIT]: added code for thing requested in comment
[编辑]:为评论中请求的事物添加了代码
回答by Ravi Kumar
If you want to change the background dynamically, use
如果要动态更改背景,请使用
YourView.setBackgroundColor(Color.argb(255, 255, 255, 255));
回答by Syed Raheem Uddin
setBackgroundDrawable is deprecated
不推荐使用 setBackgroundDrawable
Try the following simple code...
试试下面的简单代码...
Working Code:
工作代码:
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.mainLayout);
linearLayout.setBackgroundResource(R.drawable.backrepeat_blue);
enjoy
请享用
回答by Sathish
Try the following code...
试试下面的代码...
Code:
代码:
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.newImage);
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.GameLayout);
linearLayout.setBackgroundDrawable(drawable);
Hope this helps.
希望这可以帮助。