今天有用到了ListView,希望能控制List中checkbox的显示和隐藏,看到SimperAdapter源代码中一段,发现android对Listview中其他组件支持有专用接口,不用覆盖父类实现那么粗暴。
源代码如下 bindView 方法中。
private void bindView(int position, View view) {
。。。。。。
boolean bound = false;
if (binder != null) {
bound = binder.setViewValue(v, data, text);//这里使用了一个ViewBinder对象,如果binder.setViewValue(v, data, text)未处理返回false,才进行默认的值绑定,
}
if (!bound) {
if (v instanceof Checkable) {
。。。。。。
下面是自己写的ViewBinder
private class MyBinder implements SimpleAdapter.ViewBinder {
@Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
//如果是checkbox且传入了一个int型的值,则int值为显示控制。否则返回false,由simpleadapter进行默认处理。
if (view instanceof Checkable && data instanceof Integer) {
view.setVisibility((Integer) data);
return true;
}
return false;
}
}
下面是调用。
for (File curFile : file.listFiles()) {
Log.d(tag, String.format("fileList setAdapter curFile:%1$s ,curFile.canRead%2$s", curFile, curFile.canRead()));
if (curFile.isHidden() || !curFile.canRead()) {
continue;
}
HashMap<String, Object> map = new HashMap<String, Object>();
if (curFile.isDirectory()) {
map.put("img_detail", R.drawable.folder_normal);
//如果是文件夹,checkbox传入view.invisible,这是个int型常量。
map.put("checkBox_detail", View.INVISIBLE);
} else {
map.put("img_detail", R.drawable.format_unkown);
//默认传入false,不选择。
map.put("checkBox_detail", false);
}
map.put("txt_detail", curFile.getName());
map.put("file", curFile);
data.add(map);
}
Log.d(tag, String.format("fileList setAdapter"));
SimpleAdapter adapter=new SimpleAdapter(context, data, R.layout.filedetail, from, to);
//设置自定义ViewBinder到adapter。
adapter.setViewBinder(new MyBinder());