Skip to content

Instantly share code, notes, and snippets.

@JakeWharton
Created April 26, 2012 06:54
Show Gist options
  • 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);
}
}
@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