我正在尝试更改活动的背景图片 按钮单击,但无法执行此操作。你能告诉我我怎么能这样做?
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try
{
Activity activity = Selection.this;
//Drawable db = Drawable..createFromPath(R.drawable.love1);
// The below line gives error because setbackgroundImage
// is supposed to take a drawable object as an argument.
// Now what to do?
activity.findViewById(android.R.id.content)
.setBackground(Drawable.createFromPath("res/love1.jpg"));
// What to do to correct the above line?
mySong = MediaPlayer.create(Selection.this, R.raw.song1);
mySong.start();
}
catch(Exception ee){
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(ee.getMessage());
}
}
});
我使用setBackgroundColor尝试使用Color.RED,但这也无效。 PS:我没有在xml文件中更改任何内容以实现此目的。
答案 0 :(得分:4)
我认为最简单的方法是在xml
文件中使用您的活动布局..例如:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayoutID"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background_img1" >
然后根据需要将其从您的“活动”中更改为按钮点击后:
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linearLayoutID);
mLinearLayout.setBackgroundResource(R.drawable.background_img2);
答案 1 :(得分:0)
将 setBackground(可绘制)更改为 setBackgroundResource(R.drawable.filename)
答案 2 :(得分:0)
LinearLayout mLinearLayout =(LinearLayout)findViewById(R.id.LayoutID); mLinearLayout.setBackgroundResource(R.drawable.image_name);