BaseAdapter主要用于ListView(实现指定的ListAdapter接口)、Spinner(实现指定的SpinnerAdapter接口)以及GridView的共同实现一个公共基类适配器。
假设我们实现一个ArrayListAdapter,
public abstract class ArrayListAdapter<T> extends BaseAdapter{
protected ArrayList<T> mList;
protected Activity mContext;
protected ListView mListView;
public ArrayListAdapter(Activity context){
this.mContext = context;
}
@Override
//设置像layout中填充的条目数量
public int getCount() {
if(mList != null)
return mList.size();
else
return 0;
}
@Override
public Object getItem(int position) {
return mList == null ? null : mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
/**
* @param position position就是位置从0开始
* @param convertView convertView是Spinner,ListView中每一项要显示的view
* @param parent parent就是父窗体了,也就是Spinner,ListView,GridView了
* @return 通常return 的view也就是convertView
* 绘制的内容均在此实现
*/
abstract public View getView(int position, View convertView, ViewGroup parent);
public void setList(ArrayList<T> list){
this.mList = list;
notifyDataSetChanged();
}
public ArrayList<T> getList(){
return mList;
}
public void setList(T[] list){
ArrayList<T> arrayList = new ArrayList<T>(list.length);
for (T t : list) {
arrayList.add(t);
}
setList(arrayList);
}
public ListView getListView(){
return mListView;
}
public void setListView(ListView listView){
mListView = listView;
}
}