优雅的使用ViewHolder

使用ViewHolder时,每次一遍一遍的findViewById,一遍一遍在ViewHolder里面添加View的定义,view一多,是不是感觉烦爆了,base-adapter-helper这个类库似乎完美的解决了这个问题。
其设计思想是使用 SparseArray来存储view的引用,代替了原本的ViewHolder,不用声明一大堆View,简洁明了。
我也自己动手写了一个简单版的ViewHolder。
public class ViewHolder{

private final SparseArray views;
private View convertView;

private ViewHolder(View convertView){
this.views = new SparseArray();
this.convertView = convertView;
convertView.setTag(this);
}

public static ViewHolder get(View convertView){
if (convertView == null) {
return new ViewHolder(convertView);
}
ViewHolder existedHolder = (ViewHolder) convertView.getTag();
return existedHolder;
}

public T getView(int viewId) {
View view = views.get(viewId);
if (view == null) {
view = convertView.findViewById(viewId);
views.put(viewId, view);
}
return (T) view;
}
}
使用的话就超级简单和简洁了:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context)
.inflate(R.layout.good_list_item, null, false);
}

ViewHolder mViewHolder = ViewHolder.get(convertView);
TextView price = mViewHolder.getView(R.id.price);
//...其他getView

return convertView;

}

https://github.com/JoanZapata/base-adapter-helper

你可能感兴趣的:(Android,App,Development)