这些Adapter真的很多,一般情况下都是写好一个,然后用的地方复制粘贴修改。想要记住,太困难。而且各种各样的adpater需要各种各样的参数来配置,真是很烦。
这里做一次整理方便以后复制,唉。
1.ArrayAdapter
这几个是最简单形式的构造:
ArrayAdapter(Contextcontext, int textViewResourceId)
ArrayAdapter(Contextcontext, int textViewResourceId, T[] objects)
ArrayAdapter(Contextcontext, int textViewResourceId,List<T> objects)
这几个方法,构造出来的,都必须是提供一个textview的layout,没有上级容器的布局id。简单的做法就是可以直接使用,
android.R.layout.simple_list_item_1这样的系统自带的布局文件。
ArrayAdapter(Contextcontext, int resource, int textViewResourceId)
ArrayAdapter(Contextcontext, int resource, int textViewResourceId, T[] objects)
ArrayAdapter(Contextcontext, int resource, int textViewResourceId,List<T> objects)
这几个构造方法,多了一个resource,这个实际上就是可以添加一个有容器的textview。比如在一个layout里面一定要有一个textview,然后可以再放些其他东西。当然这样就必须指定出textview的ID了。就是第三个参数。
所有这些方法中,包含范型T的自定义对象,最后显示到textview上的都是这个对象的tostring方法。可以在自定义类中重写它。
以上做法都是只能操作一个textview的做法,如果要能操作更多布局上的元素,就必须使用继承了。然后通过getview来自己返回view。
如:
public class SampleAdapter extends ArrayAdapter<SampleItem> {
public SampleAdapter(Context context) {
super(context, 0);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row, null);
}
ImageView icon = (ImageView) convertView.findViewById(R.id.row_icon);
icon.setImageResource(getItem(position).iconRes);
TextView title = (TextView) convertView.findViewById(R.id.row_title);
title.setText(getItem(position).tag);
return convertView;
}
}
使用的时候,直接添加对象进入adapter
SampleAdapter adapter = new SampleAdapter(getActivity());
for (int i = 0; i < 20; i++) {
adapter.add(new SampleItem("Sample List", android.R.drawable.ic_menu_search));
}
setListAdapter(adapter);