ListView中的图像保持随机播放

时间:2017-12-11 21:30:21

标签: java android bitmap android-asynctask

我是Android新手,尝试使用异步任务加载一些图片并将其填充到ListView。但是对于我当前的代码,图像没有设置为正确的ImageViews,并且每当我滚动时它们都会改变。我找不到我犯的错误。提前谢谢。

public class BookAdapter extends ArrayAdapter<Book>  {

    public BookAdapter(Context context, ArrayList<Book> objects) {
        super(context, 0, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        View booksView = convertView;

        // inflate a view if its empty
        if (booksView == null) {
            holder = new ViewHolder();

            booksView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);

            holder.bookName = booksView.findViewById(R.id.book_name_textView);
            holder.publishedDate = booksView.findViewById(R.id.dateTextView);
            holder.bookAuthor = booksView.findViewById(R.id.author_textView);
            holder.bookImage = booksView.findViewById(R.id.book_image);


            booksView.setTag(holder);

        } else {
            holder = (ViewHolder) booksView.getTag();

        }

        Book currentBook = getItem(position);

            if (holder.bookImage != null && currentBook.getBookImage()!=null) {
                new LoadImages(holder.bookImage).execute(currentBook.getBookImage());
            }

            holder.bookName.setText(currentBook.getBookName());
            holder.bookAuthor.setText(currentBook.getAuthor());
            holder.publishedDate.setText(currentBook.getDate());

        return booksView;

    }

    private class ViewHolder {
        ImageView bookImage;
        TextView bookName;
        TextView bookAuthor;
        TextView publishedDate;
    }

}

将以下类用于asynctask

    public class LoadImages extends AsyncTask<String,Void,Bitmap>{
        private WeakReference<ImageView> imageview;
        public LoadImages(ImageView imv){
            imageview=new WeakReference<ImageView>(imv);
        }
        /** Background process
         * input:url
         * output: Bitmap image
         * It passed into onPostExecute method
         **/
        @Override
        protected Bitmap doInBackground(String... urls) {

        return QueryUtils.fetchBookImages(urls[0]);
        }

        /** This method called after the doINputBackground method
         * input:Bitmap image
         * output: image set into the image view
         * Image view  passed from RecyclerViewOperation to ShowImage class through constructor
         **/
        @Override
        protected void onPostExecute(Bitmap result) {
            if((imageview!=null)&&(result!=null)){
                ImageView imgview=imageview.get();


                if(imgview!=null){

                    imgview.setImageBitmap(result);
                }
            }
        }
    }

注意: fetchBookImages类加载返回位图。

1 个答案:

答案 0 :(得分:0)

请有众所周知的图书馆已经解决了您所面临的问题。

还有很多其他人可以找到here