认识SimpleAdapter有段时间了,始终不知道还有ViewBinder。最近在实现一个显示列表的功能时,遇到了问题,用ViewBinder可以解决。
在使用SimpleAdapter时,需要传递一个List<HashMap<String, Object>>对象,然后ListView会根据List中的数据对控件进行设置。
用String对象设置TextView,用ResourceID设置ImageView。
但是Map中的类型和空间不匹配呢,就要使用ViewBinder了。比如用Drawable对象设置ImageView。
simpleAdapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(View arg0, Object arg1, String arg2) {
// TODO Auto-generated method stub
if (arg0 instanceof ImageView && arg1 instanceof Drawable) {
ImageView view = (ImageView) arg0;
view.setImageDrawable((Drawable) arg1);
return true;
}
return false;
}
});
如果setViewValue函数返回true,则ListView不再调用getView函数。
ViewBinder的另一个用处是在getView调用之前做些其他工作,如设置监听器。
SimpleAdapter.ViewBinder binder = new SimpleAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if (view instanceof Button) {
final View button = view;
button.setOnClickListener(.......);
return false; //注意这里要返回false,因为我们的函数只是做了些额外的工作,并没有对View进行资料设置。
}
return false;
}
};
ViewBinder的接口定义如下:
/**
* This class can be used by external clients of SimpleAdapter to bind
* values to views.
*
* You should use this class to bind values to views that are not
* directly supported by SimpleAdapter or to change the way binding
* occurs for views supported by SimpleAdapter.
*
* @see SimpleAdapter#setViewImage(ImageView, int)
* @see SimpleAdapter#setViewImage(ImageView, String)
* @see SimpleAdapter#setViewText(TextView, String)
*/
public static interface ViewBinder {
/**
* Binds the specified data to the specified view.
*
* When binding is handled by this ViewBinder, this method must return true.
* If this method returns false, SimpleAdapter will attempts to handle
* the binding on its own.
*
* @param view the view to bind the data to
* @param data the data to bind to the view
* @param textRepresentation a safe String representation of the supplied data:
* it is either the result of data.toString() or an empty String but it
* is never null
*
* @return true if the data was bound to the view, false otherwise
*/
boolean setViewValue(View view, Object data, String textRepresentation);
}