我有一个简单的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;
}
}
谢谢!
答案 0 :(得分:25)
为您的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;
...
[编辑]:为评论中要求的内容添加了代码
答案 1 :(得分:3)
如果要动态更改背景,请使用
YourView.setBackgroundColor(Color.argb(255, 255, 255, 255));
答案 2 :(得分:1)
不推荐使用setBackgroundDrawable
尝试以下简单代码......
工作代码:
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.mainLayout);
linearLayout.setBackgroundResource(R.drawable.backrepeat_blue);
享受
答案 3 :(得分:0)
请尝试以下代码......
代码:
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.newImage);
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.GameLayout);
linearLayout.setBackgroundDrawable(drawable);
希望这有帮助。