在安卓(初学者级别)的列表视图延迟加载图片? [英] Lazy Load images on Listview in android(Beginner Level)?

查看:184
本文介绍了在安卓(初学者级别)的列表视图延迟加载图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/541966/android-how-do-i-do-a-lazy-load-of-images-in-listview">Android - 如何做我做的ListView图像的延迟加载

我的工作与自定义适配器列表视图。我要加载的图像和文本查看就可以了。这些图像是负载从互联网上的网址。我只是想表明这是可见的列表项兴田用户的图像。我涉及过<一个href="http://$c$c.google.com/p/shelves/source/browse/trunk/Shelves/src/org/curiouscreature/android/shelves/activity/BooksAdapter.java">Shelves开源项目例如,从romainguy ,但其复杂的了解code。对于一个初学者的水平,我只是想知道如何处理适配器和活动之间的标记。从 commonsware 例如我可以设置在适配器的标签,但不能在列表视图的空闲状态显示相应的图像。请帮我看看你的想法。样品codeS都更容易理解。

I am working on the listview with the custom adapter. I want to load the images and text view on it. The images are load from the internet urls. I just want to show the images which are visible list item to hte user. I refered the Shelves opensource project example from romainguy, but its to complicated to understand the code. For a beginner level, I just want to know how to handle the tag between the adapter and activity. From the commonsware example I can set the tag on adapter, but can't show the corresponding image at the idle state of the listview. Please help me with your ideas. Sample codes are more understandable.

感谢。

编辑:

的<一个组合href="http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html">Efficient和<一href="http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List13.html">Slow适配器ApiDemos更有助于理解。

The combination of Efficient and Slow Adapter in ApiDemos is more helpful to understand.

进行高效的适配器,例如像这样的变化:

changes done on efficient adapter example like this:

public class List14 extends ListActivity implements ListView.OnScrollListener {
// private TextView mStatus;

private static boolean mBusy = false;
static ViewHolder holder;

public static class EfficientAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    private Bitmap mIcon1;
    private Bitmap mIcon2;

    public EfficientAdapter(Context context) {
        // Cache the LayoutInflate to avoid asking for a new one each time.
        mInflater = LayoutInflater.from(context);

        // Icons bound to the rows.
        mIcon1 = BitmapFactory.decodeResource(context.getResources(),
                R.drawable.icon48x48_1);
        mIcon2 = BitmapFactory.decodeResource(context.getResources(),
                R.drawable.icon48x48_2);
    }

    /**
     * The number of items in the list is determined by the number of
     * speeches in our array.
     * 
     * @see android.widget.ListAdapter#getCount()
     */
    public int getCount() {
        return DATA.length;
    }

    /**
     * Since the data comes from an array, just returning the index is
     * sufficent to get at the data. If we were using a more complex data
     * structure, we would return whatever object represents one row in the
     * list.
     * 
     * @see android.widget.ListAdapter#getItem(int)
     */
    public Object getItem(int position) {
        return position;
    }

    /**
     * Use the array index as a unique id.
     * 
     * @see android.widget.ListAdapter#getItemId(int)
     */
    public long getItemId(int position) {
        return position;
    }

    /**
     * Make a view to hold each row.
     * 
     * @see android.widget.ListAdapter#getView(int, android.view.View,
     *      android.view.ViewGroup)
     */
    public View getView(int position, View convertView, ViewGroup parent) {
        // A ViewHolder keeps references to children views to avoid
        // unneccessary calls
        // to findViewById() on each row.

        // When convertView is not null, we can reuse it directly, there is
        // no need
        // to reinflate it. We only inflate a new View when the convertView
        // supplied
        // by ListView is null.
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item_icon_text,
                    null);

            // Creates a ViewHolder and store references to the two children
            // views
            // we want to bind data to.
            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.text);
            holder.icon = (ImageView) convertView.findViewById(R.id.icon);

            convertView.setTag(holder);
        } else {
            // Get the ViewHolder back to get fast access to the TextView
            // and the ImageView.
            holder = (ViewHolder) convertView.getTag();
        }
        if (!mBusy) {
            holder.icon.setImageBitmap(mIcon1);

            // Null tag means the view has the correct data
            holder.icon.setTag(null);
        } else {
            holder.icon.setImageBitmap(mIcon2);

            // Non-null tag means the view still needs to load it's data
            holder.icon.setTag(this);
        }
        holder.text.setText(DATA[position]);

        // Bind the data efficiently with the holder.
        // holder.text.setText(DATA[position]);

        return convertView;
    }

    static class ViewHolder {
        TextView text;
        ImageView icon;
    }
}

private Bitmap mIcon1;
private Bitmap mIcon2;
@Override
public void onCreate(Bundle savedInstanceState) {
    mIcon1 = BitmapFactory.decodeResource(this.getResources(),
            R.drawable.icon48x48_1);
    mIcon2 = BitmapFactory.decodeResource(this.getResources(),
            R.drawable.icon48x48_2);
    super.onCreate(savedInstanceState);
    setListAdapter(new EfficientAdapter(this));
    getListView().setOnScrollListener(this);
}

public void onScroll(AbsListView view, int firstVisibleItem,
        int visibleItemCount, int totalItemCount) {
}

public void onScrollStateChanged(AbsListView view, int scrollState) {
    switch (scrollState) {
    case OnScrollListener.SCROLL_STATE_IDLE:
        mBusy = false;

        int first = view.getFirstVisiblePosition();
        int count = view.getChildCount();
        for (int i = 0; i < count; i++) {

            holder.icon = (ImageView) view.getChildAt(i).findViewById(
                    R.id.icon);
            if (holder.icon.getTag() != null) {
                holder.icon.setImageBitmap(mIcon1);
                holder.icon.setTag(null);
            } 
        }

        // mStatus.setText("Idle");
        break;
    case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
        mBusy = true;
        // mStatus.setText("Touch scroll");
        break;
    case OnScrollListener.SCROLL_STATE_FLING:
        mBusy = true;
        // mStatus.setText("Fling");
        break;
    }
}
private static final String[] DATA = { "Abbaye de Belloc",
        "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
        "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu"};
}

现在工作正常。但是,当滚动状态,它不是重新加载图像正常。项目的一些间隔不显示images2。这是图像的正确顺序装载。但不在列表中的所有项目。不匹配固体物品间隔之间发生的事情。 如何纠正呢?

It works fine now. But when the scrolling state its not reloading the image properly. some interval of items not shows the images2. that is the correct order of the images are loading. But not in all items of list. Mismatches happening between solid item intervals. how to correct it?

推荐答案

普利文 -

正如你已经发现了这个我的博客文章,我只是想将它推回#1,以便其他人可以使用它。

As you already found my blog post on this, I just wanted to push it back to Stackoverflow so that others can use it.

下面是基本的讨论: 的http://ballardhack.word$p$pss.com/2010/04/05/loading-remote-images-in-a-listview-on-android/

Here's the basic discussion: http://ballardhack.wordpress.com/2010/04/05/loading-remote-images-in-a-listview-on-android/

而且还有一类我后来证明,使用一个线程,并回调加载图像:

And there's a class I documented later that uses a thread and a callback to load the images:

<一个href="http://ballardhack.word$p$pss.com/2010/04/10/loading-images-over-http-on-a-separate-thread-on-android/" rel="nofollow">http://ballardhack.word$p$pss.com/2010/04/10/loading-images-over-http-on-a-separate-thread-on-android/

更新:为了满足您的特定例外,我认为这种观点从 getChildAt 返回列表不是 ImageView的 - 这是什么版式视图中使用的是保存图像和文字。

Update: To address your specific exception, I think that view returned in the list from getChildAt is not an ImageView -- it's whatever layout view you are using to hold the image and text.

更新,包括有关code :(每@乔治收容器的建议)

Update to include relevant code: (Per @george-stocker's recommendation)

下面是我用的是适配器:

Here is the adapter I was using:

public class MediaItemAdapter extends ArrayAdapter<MediaItem> {
  private final static String TAG = "MediaItemAdapter";
  private int resourceId = 0;
  private LayoutInflater inflater;
  private Context context;

  private ImageThreadLoader imageLoader = new ImageThreadLoader();

  public MediaItemAdapter(Context context, int resourceId, List<MediaItem> mediaItems) {
    super(context, 0, mediaItems);
    this.resourceId = resourceId;
    inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.context = context;
  }

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

    View view;
    TextView textTitle;
    TextView textTimer;
    final ImageView image;

    view = inflater.inflate(resourceId, parent, false);

    try {
      textTitle = (TextView)view.findViewById(R.id.text);
      image = (ImageView)view.findViewById(R.id.icon);
    } catch( ClassCastException e ) {
      Log.e(TAG, "Your layout must provide an image and a text view with ID's icon and text.", e);
      throw e;
    }

    MediaItem item = getItem(position);
    Bitmap cachedImage = null;
    try {
      cachedImage = imageLoader.loadImage(item.thumbnail, new ImageLoadedListener() {
      public void imageLoaded(Bitmap imageBitmap) {
      image.setImageBitmap(imageBitmap);
      notifyDataSetChanged();                }
      });
    } catch (MalformedURLException e) {
      Log.e(TAG, "Bad remote image URL: " + item.thumbnail, e);
    }

    textTitle.setText(item.name);

    if( cachedImage != null ) {
      image.setImageBitmap(cachedImage);
    }

    return view;
  }
}

这篇关于在安卓(初学者级别)的列表视图延迟加载图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆