ListView very slow when scrolling (using ViewHolder/recycling)

后端 未结 10 489

I\'m back at trying out some Android dev again. I have an \"old\" HTC Hero phone lying around, so I booted that one up, did some updates and are now up n running again with Ecli

10条回答
  •  [愿得一人]
    2021-02-02 17:06

    To improve performance of listview use both or any one of the two - (Simple implementation)

    • ViewHolder
    • AsyncTask (a separate thread)

    If you have moderately long lists I recommend ViewHolder otherwise for large lists (like in the case of a music player) I recommend using ViewHolder along with AsyncTask. The key to smooth ListView scrolling is to reduce memory consumption as much as possible.

    To implement ViewHolder, is simple. Just create a static class in your custom Adapter that holds all the views that you find via findViewById. So this is how it should look -

    static class ViewHolder
    {
    TextView text;
    TextView timestamp;
    ImageView icon;
    ProgressBar progress;
    int position;
    }
    

    Then, the next time you need to findViewById any of these views, just reference the ViewHolder like this-

    ViewHolder holder = new ViewHolder();
    holder.icon = (ImageView) yourView.findViewById(R.id.listitem_image);
    holder.text = (TextView) yourView.findViewById(R.id.listitem_text);
    holder.timestamp = (TextView) yourView.findViewById(R.id.listitem_timestamp);
    holder.progress = (ProgressBar) yourView.findViewById(R.id.progress_spinner);
    

    This is tested code and taken from one of my projects. However, the original source is here - http://developer.android.com/training/improving-layouts/smooth-scrolling.html

    The lists become smoother using ViewHolder. Using AsyncTask is a little more complex, but do check out the link if you wish to implement the AsyncTask along with ViewHolder for a much smoother scrolling experience. Good Luck!

提交回复
热议问题