以前使用Listview 实现convertView的复用, 都是在Adapter中写一个静态类:
其实有时候感觉很不方便
这几天看一个开源项目, 发现使用有个大神写了一个ViewHolder.java的东西,让人耳目一新, 其实是通过一个SparseArray来缓存这些view, 省去了自己
写一堆view将来 改造也麻烦的问题 效率虽然差了一点点, 但是开发效率提高了不少
public class ViewHolder
{
final View mRoot;
//缓存item中各个view , 省去下次findviewbyid
final SparseArray<View> mViews = new SparseArray<View>();
public ViewHolder(View root)
{
this.mRoot = root;
}
@SuppressWarnings ("unchecked")
public <T extends View> T getViewById(int id)
{
T view = (T) mViews.get(id);
if (view == null)
{
mViews.put(id, (view = (T) mRoot.findViewById(id)));
if (view == null)
throw new NullPointerException("Cannot find requested view id "+String.valueOf(id));
}
return view;
}
public boolean hasView(int id)
{
if (mViews.get(id) != null) return true;
else
{
View view = this.mRoot.findViewById(id);
if (view == null) return false;
else
{
mViews.put(id, view);
return true;
}
}
}
}
测试代码:
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView listView = new ListView(this);
listView.setAdapter(new MyAdapter());
setContentView(listView);
}
private class MyAdapter extends BaseAdapter
{
@Override
public int getCount() {
return 1000;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = buildView(R.layout.layout_item, parent);
}
ViewHolder viewHolder = (ViewHolder) convertView.getTag();
TextView textView = viewHolder.getViewById(R.id.textView1);
textView.setText("Test" + position);
return convertView;
}
//把组装xml view的 函数抽取出来
protected View buildView(int redId, ViewGroup parent) {
View view = LayoutInflater.from(MainActivity.this).inflate(redId, parent, false);
view.setTag(new ViewHolder(view));
return view;
}
}
}