Created
January 9, 2015 11:03
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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