SimpleAdapter代码学习bindView

工作任务完成了,,闲来无事看看Android FrameWork层源码,SimpleAdater;


看到bindView()这个方法有这么一段:


   boolean bound = false;
      if (binder != null) {
        bound = binder.setViewValue(v, data, text);
   }
判断SimpleAdapte有没有指定SimpleAdapter.ViewBinder,如果指定了就调用其setViewValue方法, SimpleAdapter.ViewBinder是一个接口,也只有这一个方法,如果ViewBinder返回true表示我们已经完成了对这个View的数据绑定,就不再调用系统默认的实现;
嘿嘿,貌似以前复写SimpleAdapter,BaseAdapter的时候,都没有关注过这个。

 /**
     * 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);
    }

在这个 setViewValue中,我们可以做一些事情,可以在系统绑定数据之前做些事情,如:在Item中动态添加事件,或者添加删除view;再手动返回false或都true,控制是否再,由系统来默认实现;
 SimpleAdapter.ViewBinder binder = new SimpleAdapter.ViewBinder() {

            @Override
            public boolean setViewValue(View view, Object data, String textRepresentation) {
                if (view instanceof Button) {
                    final View button = view;
                    LinearLayout listItem = (LinearLayout) button.getParent();
                    TextView textView = new TextView(AdapterDemoActivity.this);
                    textView.setText("AA");
                    listItem.addView(textView,new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                    return false;
                }
                return false;
            }
        };

adapter.setViewBinder(binder);


你可能感兴趣的:(Android)