动态设置线性布局背景

19
我希望以以下方式动态设置线性布局的背景:
  1. 通过XML解析从Web URL获取图片,然后将该图像存储到SD卡中。

  2. 现在图片已保存到SD卡中。

  3. 将该图片设置为应用程序中线性布局的背景。

现在我卡在第三步。有人能帮忙吗?

http://developerlife.com/tutorials/?p=312 - Nikunj Patel
7个回答

51

1
你确定图片正在被正确下载和保存吗?它是否存在? - Deimos
这需要API 16。有没有更低API的其他方法? - Marek
据我所记,这不需要API 16。 - Deimos
2
BitmapDrawable已被弃用。 - user1940676
1
new BitmapDrawable(bmImg)已经被弃用,请使用new BitmapDrawable(getContext().getResources(), bmImg)代替。 - Janneman96
显示剩余6条评论

5
我已经这样做了:
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();

异步任务用于在后台加载图片:

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);
    }
}

希望这能对你有所帮助。


4

API已过时,您可以使用以下代码

BitmapDrawable background = new BitmapDrawable(getResources(), bitmapImage);
linearLayout.setBackground(background);

4
更简单的方法:
BitmapDrawable d = new BitmapDrawable("/sdcard/data/image.jpg");
linearLayout.setBackgroundDrawable(d);

0
使用@Deimos的答案,但是像这样,因为现在有些方法已经过时了。
Bitmap bmImg = BitmapFactory.decodeStream(is);
BitmapDrawable background = new BitmapDrawable(context.getResources(), bmImg);
linearLayout.setBackground(background);

0

尝试使用这个:

Bitmap bmpOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.img);
BitmapDrawable bmpBackground = new BitmapDrawable(getResources(), bmpOriginal)

-1

你也可以从drawable文件夹中设置图片。

yourView.setBackgroundResource(R.drawable.FILENAME);

这将FILENAME设置为背景图像。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接