Skip to content

Instantly share code, notes, and snippets.

@Phocacius
Created January 9, 2015 11:03
Show Gist options
  • Save Phocacius/28141d98953911dd6d91 to your computer and use it in GitHub Desktop.
Save Phocacius/28141d98953911dd6d91 to your computer and use it in GitHub Desktop.
A generic Android ViewHolder class that simplifies the standard ViewHolder pattern. Credit goes to http://www.piwai.info/android-adapter-good-practices/
public class ViewHolder {
@SuppressWarnings("unchecked")
public static <T extends View> T get(View view, int id) {
SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
if (viewHolder == null) {
viewHolder = new SparseArray<View>();
view.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if (childView == null) {
childView = view.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
}
// USAGE in getView() of a BaseAdapter
// if (convertView == null) {
// convertView = LayoutInflater.from(context).inflate(R.layout.my_layout, parent, false);
// }
// ImageView bananaView = ViewHolder.get(convertView, R.id.banana);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment