GridView scrolling problem on Android

后端 未结 5 1645
走了就别回头了
走了就别回头了 2021-02-02 03:06

this must be somethng very simple I\'m overlooking, but I have the following problem (the post is rather lengthy, but I want to provide as much info as possible :) ).

I

5条回答
  •  轮回少年
    2021-02-02 03:28

    The answer is view recycling.

    In general your getView should always be something of the form:

    public class ImageAdapter extends BaseAdapter {
    
        private List mUrls; // put your urls here
        private Map mImages; // cache your images here
    
        public ImageAdapter() {
            ...
            mUrls = new ArrayList();
            mImages = new HashMap();
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder; // Use the ViewHolder pattern for efficiency
    
            if (convertView == null) {
                // first time this view has been created so inflate our layout
                convertView = View.inflate(this, R.layout.my_grid_item, null);
                holder = new ViewHolder();
                holder.image = convertView.findViewById(R.id.image);
                holder.text = convertView.findViewById(R.id.text);
                convertView.setTag(holder); // set the View holder
            } else {
               holder = (ViewHolder) convertView.getTag();
            }
    
            // update the current view - this must be done EVERY
            // time getView is called due to view recycling
            holder.text.setText(Integer.toString(position));
    
            // check our cache for the downloaded image
            final String url = mUrls.get(position);
            if (mImages.get(url) != null)
                holder.image.setImageDrawable(mImages.get(url));
            else
                loadImage(url, holder.image);
    
            // return our view
            return convertView;
        }
    
        public loadImage(final String url, final ImageView image) {
            // load an image (maybe do this using an AsyncTask
            // if you're loading from network
        }
    
        ...
    }
    

    Where your ViewHolder class would look something like

    public class ViewHolder {
        ImageView thumbImage;
        TextView text;
    }
    

    Then you shouldn't run into any problems. Also I'm not sure why you needed to sleep in your getView? That will slow down scrolling of your GridView.

提交回复
热议问题