我希望以以下方式动态设置线性布局的背景:
通过XML解析从Web URL获取图片,然后将该图像存储到SD卡中。
现在图片已保存到SD卡中。
将该图片设置为应用程序中线性布局的背景。
通过XML解析从Web URL获取图片,然后将该图像存储到SD卡中。
现在图片已保存到SD卡中。
将该图片设置为应用程序中线性布局的背景。
使用这个:
Bitmap bmImg = BitmapFactory.decodeStream(is);
BitmapDrawable background = new BitmapDrawable(bmImg);
linearLayout.setBackgroundDrawable(background);
还可以查看这个:如何在Android中将Bitmap转换为Drawable?
new BitmapDrawable(bmImg)
已经被弃用,请使用new BitmapDrawable(getContext().getResources(), bmImg)
代替。 - Janneman96private RelativeLayout relativeLayout;
onCreate:
relativeLayout= (RelativeLayout)findViewById(R.id.relativeLayout);
new LoadBackground("http://www.tmonews.com/wp-content/uploads/2012/10/androidfigure.jpg",
"androidfigure").execute();
异步任务用于在后台加载图片:
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);
}
}
希望这能对你有所帮助。
API已过时,您可以使用以下代码
BitmapDrawable background = new BitmapDrawable(getResources(), bitmapImage);
linearLayout.setBackground(background);
BitmapDrawable d = new BitmapDrawable("/sdcard/data/image.jpg");
linearLayout.setBackgroundDrawable(d);
Bitmap bmImg = BitmapFactory.decodeStream(is);
BitmapDrawable background = new BitmapDrawable(context.getResources(), bmImg);
linearLayout.setBackground(background);
尝试使用这个:
Bitmap bmpOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.img);
BitmapDrawable bmpBackground = new BitmapDrawable(getResources(), bmpOriginal)
你也可以从drawable文件夹中设置图片。
yourView.setBackgroundResource(R.drawable.FILENAME);
这将FILENAME设置为背景图像。