通常,很多人都是把Adapter内嵌在Activity,而且Adapter的数据集合也是Activity的成员变量,因此经常发生数据集合为null引起的崩溃,调用Adapter.notifySetDataChanged()界面有时候并没有刷新。
建议保持一种Adapter编写风格,这样可以方便错误排查,和ListView、GridView相关的Adapter全部都继承BaseAdapter,并且数据字典由构造函数直接注入,自定义刷新方法并传入新数据,确保界面的有效刷新。模板代码如下:
public class TestAdapter<T> extends BaseAdapter {
private List<T> mList;
private Context mContext;
public TestAdapter(List<T> mList, Context mContext) {
super();
this.mList = mList;
this.mContext = mContext;
}
public void refresh(List<T> mList){
this.mList = mList;
this.notifyDataSetChanged();
}
@Override
public int getCount() {
return mList == null ? 0 : mList.size();
}
@Override
public T getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView==null){
convertView = View.inflate(mContext, R.layout.item_layout, null);
holder = new ViewHolder();
holder.ivTest = ViewUtils.findViewById(convertView, R.id.iv_test);
holder.tvTest = ViewUtils.findViewById(convertView, R.id.tv_test);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
// TODO Auto-generated method stub
return convertView;
}
static class ViewHolder {
TextView tvTest;
ImageView ivTest;
}
}
可能觉得有点老生常谈,对于初学者而言,看起来似乎都会写,但能够保证不出问题,就是一种能力了。