这里做的是一个文件浏览器,ListView首先不继承ListActivity,main.xml中定义一个ListView,而在list_data.xml中定义ListView每一行的数据项,这里有一个TextView和checkbox。要知道ListView最终要存的是一个Adapter,而Adapter有三种,这里只介绍baseAdapter,因为其余两种比较简单,而baseAdapter主要的工作在于getView()方法,此方法能根据外界所传进来的资源id去生成一个列表项。而要取得ListView上面的checkbox控件,需要有private LayoutInflater inflater;这个变量用来获取list_data.xml里面的控件,具体实现是view = inflater.inflate(R.layout.list_data, null);这个view可以通过findviewbyid获取到checkbox的id.可以实现对checkbox的操作。
MyAdapter继承baseAdapter,构造函数实现数据的传递,最重要的是构造LayoutInflater,inflater = LayoutInflater.from(context);context为设备上下文,通常传递this
public MyAdapter(Context context, List<HashMap<String, Object>> list,
int resource, String[] from, int[] to) {
this.context = context;
this.list = list;
keyString = new String[from.length];
idValue = new int[to.length];
System.arraycopy(from, 0, keyString, 0, from.length);
System.arraycopy(to, 0, idValue, 0, to.length);
inflater = LayoutInflater.from(context);
init();
}
init()将checkbox全部设定为未选中,定义一个public static HashMap<Integer, Boolean> isSelected;存放每一个checkbox的状态,在getview方法中设置给checkbox,此时也可设置是否显示checkbox。
以上就是我们封装的Adapter类。
利用这个Adapter类进行listView的显示,ListView单击事件 datalist.setOnItemClickListener(new OnItemClickListener(){});
ListView长按事件 datalist.setOnItemLongClickListener(new OnItemLongClickListener(){});
通过ViewHolder取得当前点击的List,ViewHolder holder = (ViewHolder) view.getTag();
getTag能够取得当前点击的视图标签,从而判定当前选中的是哪个checkbox,holder.cb.toggle();// 在每次获取点击的item时改变checkbox的状态
MyAdapter.isSelected.put(position, holder.cb.isChecked()); // 同时修改map的值保存状态