Recycling views in custom array adapter: how exactly is it handled?

后端 未结 5 894
栀梦
栀梦 2020-12-15 11:15

I am having an unclear issue concerning the recycling of views in a getView method of a custom array adapter.

I understand that elements are reused, but how do I kn

5条回答
  •  情书的邮戳
    2020-12-15 11:58

    The last part of the question I really couldn't grasp without a picture of the effect but for the first part "what to implement in the first part of the if statement, and what in the second" I think I've found the this implementation very common.

    You would find the view references first and store them to a static class ViewHolder which then you attach to the tag of the new inflated view. As the listview recycles the views and a convertView is passed getView you get the ViewHolder from the convertView's tag so you don't have to find the references again (which greatly improves performance) and update the view data with that of your object at the position given.

    Technically you don't care what position the view was since all you care for is the references to the views you need to update which are held within it's ViewHolder.

    @Override
    public View getView(int position, View convertView, ViewGroup container) {
        ViewHolder holder;
        Store store = getItem(position);
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.item_store, null);
    
            // create a holder to store references
            holder = new ViewHolder();
    
            // find references and store in holder
            ViewGroup logoPhoneLayout = (ViewGroup) convertView
                    .findViewById(R.id.logophonelayout);
            ViewGroup addressLayout = (ViewGroup) convertView
                    .findViewById(R.id.addresslayout);
    
            holder.image = (ImageView) logoPhoneLayout
                    .findViewById(R.id.image1);
            holder.phone = (TextView) logoPhoneLayout
                    .findViewById(R.id.textview1);
            holder.address = (TextView) addressLayout
                    .findViewById(R.id.textview1);
    
            // store holder in views tag
            convertView.setTag(holder);
        } else {
    
            // Retrieve holder from view
            holder = (ViewHolder) convertView.getTag();
        }
    
        // fill in view with our store (at this position)
        holder.phone.setText(store.phone);
        holder.address.setText(store.getFullAddress());
    
        UrlImageViewHelper.setUrlDrawable(holder.image, store.storeLogoURL,
                R.drawable.no_image);
    
        return convertView;
    }
    
    private static class ViewHolder {
        ImageView image;
        TextView phone;
        TextView address;
    }
    

提交回复
热议问题