Skip to content

Instantly share code, notes, and snippets.

@JakeWharton
Created April 26, 2012 06:54
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JakeWharton/2496926 to your computer and use it in GitHub Desktop.
Save JakeWharton/2496926 to your computer and use it in GitHub Desktop.
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);
}
}
@ducky-hong
Copy link

Interesting. But what if there are two or more view types in the list ?

@JakeWharton
Copy link
Author

This was just a base case for someone that was asking about it in the Android developer chat. Obviously if you are supporting more advanced features of a list adapter you will need to accomodate accordingly.

@jophde
Copy link

jophde commented Apr 26, 2012

Where is the Android developer chat?

@JakeWharton
Copy link
Author

@jophde
Copy link

jophde commented Apr 26, 2012

Can the ViewHolder class be nested inside of a static class that is already nested? I usually put my adapters inside of my ListActivity. On lines 25 and 26, don't you need to cast View returned from findViewById to a TextView? Also, should get view return vh.root? I am trying this out on one of my classes and getting issues with the LayoutInflater.

@JakeWharton
Copy link
Author

Yes. It was just a quick example of the pattern. Not meant to be a 100% drop-in solution.

@jophde
Copy link

jophde commented Apr 26, 2012

Ok cool just wanted to make sure. Thanks it works great! My lists are iPhone smooth now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment