【发布时间】:2015-06-26 11:15:40
【问题描述】:
我正在尝试更改活动的背景图片 单击按钮,但无法这样做。你们能告诉我我该怎么做吗?
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 文件中的任何内容来完成此操作。
【问题讨论】:
-
请提供
.setBackground中抛出的错误,并查看Drawable.createFromPath()返回的内容(它确实是可绘制对象吗?createFromPath成功了吗?) -
实际上没有抛出任何错误,唯一的问题是当我尝试使用 Drawable.createFrompath() 时,它说我所需的最低 API 级别是 16,而您使用的低于该级别。但是颜色的东西现在正在起作用。只有我无法更改背景。这次我遇到的问题是: 1. 我在 xml 的 Layout 标记中添加了一个 id,然后使用该 id 来更改颜色。 2.但我不能对背景(Drwawable)做同样的事情,因为它需要一个我无法提供的可绘制参数,并且请不要使用你上面的方法它不工作!!
-
使用
getResources().getDrawable(R.drawable.your_drawable)并将你的drawable(jpg)放在res/drawable文件夹中。您不能在 API 级别低于 16 的情况下使用setBackground,您应该为此使用setBackgroundDrawable。 Source and example on API level-dependent execution
标签: android android-intent android-fragments android-activity