-
-
Save JakeWharton/2496926 to your computer and use it in GitHub Desktop.
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); | |
} | |
} |
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.
Where is the Android developer chat?
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.
Yes. It was just a quick example of the pattern. Not meant to be a 100% drop-in solution.
Ok cool just wanted to make sure. Thanks it works great! My lists are iPhone smooth now.
Interesting. But what if there are two or more view types in the list ?