SimpleAdapter中ViewBinder 使用

认识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); 
   } 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值