在ListVIew做复用优化的时候,经常会写ViewHolder,还需要很麻烦的去findview,我最讨厌写一堆的这样代码了,今天看到了一个极简的写法,很好用,很简洁啊!!!
public
static <T
extends View> T getAdapterView(View convertView,
int id) {
SparseArray<View> viewHolder = (SparseArray<View>) convertView.getTag();
if (viewHolder == null) {
viewHolder = new SparseArray<View>();
convertView.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if (childView == null) {
childView = convertView.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
SparseArray<View> viewHolder = (SparseArray<View>) convertView.getTag();
if (viewHolder == null) {
viewHolder = new SparseArray<View>();
convertView.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if (childView == null) {
childView = convertView.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
用法:
@Override
public View getView( int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_feed_item, parent, false);
}
ImageView thumnailView = getAdapterView(convertView, R.id.video_thumbnail);
ImageView avatarView = getAdapterView(convertView, R.id.user_avatar);
ImageView appIconView = getAdapterView(convertView, R.id.app_icon);
public View getView( int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_feed_item, parent, false);
}
ImageView thumnailView = getAdapterView(convertView, R.id.video_thumbnail);
ImageView avatarView = getAdapterView(convertView, R.id.user_avatar);
ImageView appIconView = getAdapterView(convertView, R.id.app_icon);
}
我的github地址:https://github.com/flyme2012
我的博客地址:http://www.cnblogs.com/flyme2012/