Tuesday, 5 March 2013

How to implement a view holder?



        @Override
        public View getView(int position, View v, ViewGroup parent) {
            // Keeps reference to avoid future findViewById()
            ContactsViewHolder viewHolder;
    
            if (v == null) {
                LayoutInflater li = (LayoutInflater) getContext().getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);
                v = li.inflate(R.layout.contact_row, parent, false);
    
                viewHolder = new ContactsViewHolder();
                viewHolder.txName = (TextView) v.findViewById(R.id.tvName);
                viewHolder.txEmails = (TextView) v.findViewById(R.id.tvEmails);
                viewHolder.txPhones = (TextView) v.findViewById(R.id.tvNumbers);
    
                v.setTag(viewHolder);
            } else {
                viewHolder = (ContactsViewHolder) v.getTag();
            }
    
            Contact contact = contacts.get(position);
            if (contact != null) {
                viewHolder.txName.setText(contact.getName());
                viewHolder.txEmails.setText(contact.getEmails().toString());
                viewHolder.txPhones.setText(contact.getNumbers().toString());
            }
            return v;
        }
    
        static class ContactsViewHolder {
            TextView txName;
            TextView txEmails;
            TextView txPhones;
        }
    }

No comments:

Post a Comment