将图片从URL加载到ListView中的图像视图

时间:2017-04-11 12:49:59

标签: android image listview custom-adapter

我有一个带自定义适配器的android Listview。列表视图中的每个项目都在图像视图中包含新闻图片,并且需要使用其URL加载图像。我的代码如下。当我运行它时,我只得到前几个项目的图片。当我向下滚动到其余项目时,我会看到每个图像视图中的进度条永远旋转。我可以在日志中看到一些图片无法加载,但我不明白为什么这会影响所有图片,因为我正在处理异常。如果我能知道自己犯了什么错误,我将感激不尽。

以下是我的自定义适配器

public class CustomAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private ArrayList<CustomObject> objects;
    private Activity activity;
    private ArrayList<Bitmap> newsImageList;

    private class ViewHolder {
        TextView titleTextView;
        TextView dateTextView;
        TextView bodyTextView;
        ImageView logoView;
        ImageView newsImageView;
        ProgressBar progressBar;
    }


    public CustomAdapter(Context context, ArrayList<CustomObject> objects, Activity activity) {
       // super(context, R.layout.news_item, objects);

        inflater = LayoutInflater.from(context);
        this.objects = objects;
        this.activity= activity;
        this.newsImageList= new ArrayList<Bitmap>();
        for(int i=0; i<objects.size(); i++)
            newsImageList.add(null);

    }

    @Override
    public int getCount() {
        return objects.size();
    }

    @Override
    public CustomObject getItem(int position) {
        return objects.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        System.out.println("IN GET VIEW");

        ViewHolder holder = null;
        if(convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.news_item, null);

            holder.titleTextView = (TextView) convertView.findViewById(R.id.txtTitle);
            holder.dateTextView = (TextView) convertView.findViewById(R.id.txtDate);
            holder.bodyTextView = (TextView) convertView.findViewById(R.id.txtBody);
            holder.logoView= (ImageView)  convertView.findViewById(R.id.source_imageView);
            holder.newsImageView= (ImageView) convertView.findViewById(R.id.news_imageView);
            holder.progressBar= (ProgressBar) convertView.findViewById(R.id.img_progress_bar);


            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.titleTextView.setText(objects.get(position).getTitle());
        holder.dateTextView.setText(objects.get(position).getDate());
        holder.bodyTextView.setText(objects.get(position).getBody());

        //for the source logo
        String uri = "@drawable/"+objects.get(position).getSource_logo()+"_logo";
        int imageResource = activity.getResources().getIdentifier(uri, null, activity.getPackageName());
        Drawable res =activity.getResources().getDrawable(imageResource);
        holder.logoView.setImageDrawable(res);





        //the news image
        String newsImageURL = objects.get(position).getNewsImageURL();

        if(newsImageURL!=null) {
            // show The Image in a ImageView

            //already loaded
            if(newsImageList.get(position)!=null) {
                holder.progressBar.setVisibility(View.INVISIBLE);
                holder.newsImageView.setImageBitmap(newsImageList.get(position));
            }
            else
                new DownloadImageTask(holder.newsImageView, holder, position)
                    .execute(newsImageURL);
        }
        else
        {
            System.out.println("NO IMAGE");
            //adjusting the view
            holder.progressBar.setVisibility(View.INVISIBLE);
            holder.newsImageView.setVisibility(View.GONE);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.bodyTextView.getLayoutParams();
            params.addRule(RelativeLayout.BELOW, R.id.txtDate);
        }


        return convertView;
    }

    //subclass
    class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;
        boolean imageLoadingFailure=false;//default is false
        ViewHolder holder;
        int index;

        public DownloadImageTask(ImageView bmImage,ViewHolder holder, int index) {
            this.bmImage = bmImage;
            this.holder= holder;
            this.index=index;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            holder.newsImageView.setImageResource(android.R.color.transparent);//clear the news image view
            holder.progressBar.setVisibility(View.VISIBLE);//show the progress bar
            holder.newsImageView.setVisibility(View.VISIBLE);//show the image view

        }

        protected Bitmap doInBackground(String... urls) {
            return downloadBitmap(urls[0]);
        }

        protected void onPostExecute(Bitmap result) {

            if(imageLoadingFailure)
            {
                //adjusting the view
                System.out.println("IMAGE LOADING FAILED!");

                /*
                holder.progressBar.setVisibility(View.INVISIBLE);
                holder.newsImageView.setVisibility(View.GONE);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.bodyTextView.getLayoutParams();
                params.addRule(RelativeLayout.BELOW, R.id.txtDate);
                */
            }
            else {
                holder.progressBar.setVisibility(View.INVISIBLE);
                bmImage.setImageBitmap(result);
                newsImageList.set(index, result);
            }



        }

        //code source: http://stacktips.com/tutorials/android/loading-image-asynchronously-in-android-listview
        private Bitmap downloadBitmap(String url) {
            HttpURLConnection urlConnection = null;
            try {
                URL uri = new URL(url);
                urlConnection = (HttpURLConnection) uri.openConnection();
                int statusCode = urlConnection.getResponseCode();
            /*if (statusCode != HttpStatus.SC_OK) {
                return null;
            }*/

                InputStream inputStream = urlConnection.getInputStream();
                if (inputStream != null) {
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                }
            } catch (Exception e) {
                urlConnection.disconnect();
                imageLoadingFailure=true;
                Log.w("ImageDownloader", "Error downloading image from " + url);
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
            return null;
        }



    }





}

以下是ListView

中每个项目的xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dip"
        android:textSize="16dip"
        android:textStyle="bold"
        android:gravity="right"
        android:textDirection="rtl"
        >
    </TextView>

    <ImageView
        android:id="@+id/source_imageView"
        android:layout_height="60dp"
        android:layout_width="60dp"
        android:layout_marginRight="10dp"
        android:layout_below="@+id/txtTitle"
        android:layout_marginTop="-15dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        />
    <TextView
        android:id="@+id/txtDate"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dip"
        android:textSize="16dip"
        android:gravity="right"
        android:textDirection="rtl"
        android:textStyle="italic"
        android:layout_below="@id/source_imageView"
        android:layout_marginTop="-20dp"
        >
    </TextView>

    <RelativeLayout
        android:id="@+id/relative_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtDate"
        android:layout_centerInParent="true">
        <ImageView
            android:id="@+id/news_imageView"
            android:layout_height="200dp"
            android:layout_width="340dp"
            android:layout_centerInParent="true"
            />
        <ProgressBar
            android:id="@+id/img_progress_bar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminate="true"
            android:layout_centerInParent="true"/>
    </RelativeLayout>


    <TextView
        android:id="@+id/txtBody"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dip"
        android:textSize="16dip"
        android:gravity="right"
        android:textDirection="rtl"
        android:layout_below="@id/relative_container"
        >
    </TextView>


</RelativeLayout>

1 个答案:

答案 0 :(得分:1)

使用Picasso

compile 'com.squareup.picasso:picasso:2.5.2'

代码

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);