简体   繁体   English

将listview项目背景图像设置为从Web下载的可绘制对象

[英]Setting listview item background image to drawable downloaded from the web

I'm downloading an image from the web and trying to set it as the background to the inflated list element in my ListView adapter. 我正在从网上下载图像,并尝试将其设置为ListView适配器中膨胀列表元素的背景。 This is my method (from the class extending BaseAdapter : 这是我的方法(来自扩展BaseAdapter的类:

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    //working with an object called "hl"
    if (view == null){
        view = myInflater.inflate(R.layout.list_element, null);
    }

    Bitmap background = hl.getBgImage();
    Drawable dr = new BitmapDrawable(background);
    RelativeLayout rl = (RelativeLayout) view.findViewById(R.layout.headline_list);
    rl.setBackgroundDrawable(dr);
    return view;
}

However, I am getting a NullPointerException on the rl.setBackgroundDrawable(dr); 但是,我在rl.setBackgroundDrawable(dr);上收到NullPointerException rl.setBackgroundDrawable(dr); line. 线。 Is there a problem with the way I'm adding the image? 我添加图像的方式是否有问题? My method to get the bitmap is as follows, the stack trace is never called so I assume that it is downloading properly? 我获取位图的方法如下,从不调用堆栈跟踪,因此我假设它下载正确?

private static Bitmap getBitmapFromURL(String imageUrl) {
    try {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

Thanks for any advice. 感谢您的任何建议。

Edit: I am calling getBitmapFromUrl(String imageURL) with: 编辑:我正在调用getBitmapFromUrl(String imageURL)与:

    String image = "http://www.google.com/trends/resources/2327917647-google-icon.png";
    Bitmap bg = getBitmapFromURL(image);
    Object hl = new Object(title, bg);
    objectList.add(hl);

Found the issue. 找到了问题。 Should have ignored the relativelayout completely. 应该完全忽略了相对布局。

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    //working with an object called "hl"
    if (view == null){
        view = myInflater.inflate(R.layout.headline_list, null);
    }

    Bitmap background = hl.getBgImage();
    Drawable dr = new BitmapDrawable(background);
    view.setBackgroundDrawable(dr);
    return view;
}

As I know, the code line "rl.setBackgroundDrawable(dr);" 据我所知,代码行“ rl.setBackgroundDrawable(dr);” will never throw NullPointerException unless rl is null, even if dr is null. 除非rl为null,否则将永远不会抛出NullPointerException,即使dr为null。 So Please update your xml file R.layout.list_element and let's find the problem together. 因此,请更新您的xml文件R.layout.list_element,让我们一起查找问题。 Good Luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM