ListView BaseAdapter 的封装
1、MyBaseAdapter的写法
继承BaseAdapter
getCount/getItem/getItemId通用写法
getView 获取holder、设置数据,由于getView 返回的具体条目的属性不确定,故抽象出来,由子类具体实现
@Override
public View getView(int position, View convertView, ViewGroup parent) {
BaseHolder holder=null;
if (null ==convertView){
holder = getHolder(mContext);
}else {
holder = (BaseHolder) convertView.getTag();
}
holder.setData(mList.get(position));
return holder.convertView;
}
2、BaseHolder 的写法
对于不确定的数据类型使用泛型
对于不确定的initView采用抽象
public View convertView;
public T data;
public BaseHolder(Context context) {
convertView = initView(context);
convertView.setTag(this);
}
public void setData(T t) {
data = t;
refreshView();
}
protected abstract void refreshView();
public abstract View initView(Context context) ;
3、具体Adapter(StringAdapter)的写法
创建具体的Holder
public StringAdapter(Context context, List list) {
super(context, list);
}
@Override
public BaseHolder getHolder(Context context) {
return new StringHolder(context);
}
4、具体Holder(StringHolder)的写法
加载相应的布局文件
初始化相应的控件
刷新控件
public class StringHolder extends BaseHolder<String> {
private TextView mTextView;
public StringHolder(Context context) {
super(context);
}
@Override
public View initView(Context context) {
View itemView = View.inflate(context, R.layout.item_list, null);
mTextView = itemView.findViewById(R.id.tvItem);
return itemView;
}
@Override
protected void refreshView() {
mTextView.setText(data);
}
}
最后一步使用
private List<String> mDataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = findViewById(R.id.lvListView);
Button changeBtn = findViewById(R.id.btnChange);
mDataList = new ArrayList<>();
for (int i = 0; i < 30; i++) {
mDataList.add(" I Love you "+ i);
}
final StringAdapter stringAdapter = new StringAdapter(this, mDataList);
listView.setAdapter(stringAdapter);
changeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
changeData();
stringAdapter.notifyDataSetChanged();
}
});
}
private void changeData() {
mDataList.clear();
for (int i = 0; i < 50; i++) {
mDataList.add("I love China too" + i);
}
}