【发布时间】:2011-11-30 14:21:54
【问题描述】:
我想通过以下方式动态设置线性布局背景:
通过 XML 解析从 web url 获取图像,然后将该图像存储到 sd 卡中。
现在将图像保存到 sd 卡中。
在应用中将该图像设置为线性布局背景。
现在我被困在第三步了。有人可以帮忙吗?
【问题讨论】:
标签: android android-layout android-widget
我想通过以下方式动态设置线性布局背景:
通过 XML 解析从 web url 获取图像,然后将该图像存储到 sd 卡中。
现在将图像保存到 sd 卡中。
在应用中将该图像设置为线性布局背景。
现在我被困在第三步了。有人可以帮忙吗?
【问题讨论】:
标签: android android-layout android-widget
使用这个:
Bitmap bmImg = BitmapFactory.decodeStream(is);
BitmapDrawable background = new BitmapDrawable(bmImg);
linearLayout.setBackgroundDrawable(background);
【讨论】:
bmImg = BitmapFactory.decodeStream(is);BitmaBitmapDrawable background = new BitmapDrawable(bmImg);linearLayout.setBackgroundDrawable(background);
new BitmapDrawable(bmImg) 已弃用。请改用new BitmapDrawable(getContext().getResources(), bmImg)。
我是这样做的:
private RelativeLayout relativeLayout;
onCreate:
relativeLayout= (RelativeLayout)findViewById(R.id.relativeLayout);
new LoadBackground("http://www.tmonews.com/wp-content/uploads/2012/10/androidfigure.jpg",
"androidfigure").execute();
AsyncTask 在背景中加载图像:
private class LoadBackground extends AsyncTask<String, Void, Drawable> {
private String imageUrl , imageName;
public LoadBackground(String url, String file_name) {
this.imageUrl = url;
this.imageName = file_name;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Drawable doInBackground(String... urls) {
try {
InputStream is = (InputStream) this.fetch(this.imageUrl);
Drawable d = Drawable.createFromStream(is, this.imageName);
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
@Override
protected void onPostExecute(Drawable result) {
super.onPostExecute(result);
relativeLayout.setBackgroundDrawable(result);
}
}
希望这会对你有所帮助。
【讨论】:
更简单的方法:
BitmapDrawable d = new BitmapDrawable("/sdcard/data/image.jpg");
linearLayout.setBackgroundDrawable(d);
【讨论】:
API 已弃用,您可以使用以下代码
BitmapDrawable background = new BitmapDrawable(getResources(), bitmapImage);
linearLayout.setBackground(background);
【讨论】:
尝试使用这个:
Bitmap bmpOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.img);
BitmapDrawable bmpBackground = new BitmapDrawable(getResources(), bmpOriginal)
【讨论】:
使用@Deimos 的答案,但是因为某些方法现在已弃用,所以像这样
Bitmap bmImg = BitmapFactory.decodeStream(is);
BitmapDrawable background = new BitmapDrawable(context.getResources(), bmImg);
linearLayout.setBackground(background);
【讨论】:
你也可以从drawable文件夹中设置图片。
yourView.setBackgroundResource(R.drawable.FILENAME);
将 FILENAME 设置为背景图像。
【讨论】: