morristech
5/10/2018 - 8:44 AM

Template for a list adapter which uses a view holder to cache lookups.

Template for a list adapter which uses a view holder to cache lookups.

public class TweetAdapter extends BaseAdapter {
    // ...

    public View getView(int position, View convertView, ViewGroup parent) {
        TweetViewHolder vh = TweetViewHolder.get(convertView, parent);
        Tweet item = getItem(position);
    
        vh.user.setText(item.user);
        vh.tweet.setText(item.tweet);

        return vh.root;
    }
}

//By making this its own class we allow for reuse in other adapters
public class TweetViewHolder {
    public static TweetViewHolder get(View convertView, ViewGroup parent) {
        if (convertView == null) {
            return new TweetViewHolder(parent);
        }
        return (TweetViewHolder)convertView.getTag(); 
    }
 
    public final View root;
    public final TextView user;
    public final TextView tweet;
    
    private TweetViewHolder(ViewGroup parent) {
        root = LayoutInflater.from(parent.getContext()).inflate(R.layout.tweet_view, parent, false);
        root.setTag(this);
     
	user = (TextView)root.findViewById(R.id.user);
	tweet = (TextView)root.findViewById(R.id.tweet);
    }
}