搞定Android DataBinding-02

RecyclerView.Adapter使用DataBinding

在Adapter中使用分三步:

  1. ViewHolder的创建
  2. 绑定ViewHolder
  3. Item数据的读取

ViewHolder的创建

inflate生成View,然后DataBindingUtil.bind(itemView)创建DataBinding
或者
RecyclerItemViewBinding.inflate()生成DataBinding,然后binding.getRoot()得到View
这里采用第一种方式

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recycler_item_view, parent, false);

        return new VehicleListAdapter.ViewHolder(view);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        //binding 用来设置绑定值
        private ViewDataBinding binding;

        public ViewHolder(View itemView) {
            super(itemView);
            binding = DataBindingUtil.bind(itemView);
        }

        public ViewDataBinding getBinding() {
            return binding;
        }
    }

绑定ViewHolder

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final VehicleInfo info = getItem(position);
        if(holder instanceof ViewHolder){
            ViewDataBinding binding = ((ViewHolder) holder).getBinding();
            binding.setVariable(BR.info, info);
            binding.setVariable(BR.itemCLick, itemListener);
            binding.setVariable(BR.selectedCLick, selectedListener);
            //等到绑定完成
            binding.executePendingBindings();
        }
    }

Item数据的读取

DataBindingUtil.findBinding(v) 方法,返回view的DataBinding,非常棒。

    OnViewClickListener itemListener = new OnViewClickListener() {

        @Override
        public void onClick(View v) {
            RecyclerItemViewBinding binding = DataBindingUtil.findBinding(v);
            VehicleInfo data = binding.getInfo();
            Toast.makeText(v.getContext(), data.getBrand(), Toast.LENGTH_SHORT).show();
        }
    };

NotifyDataChanged

Data Binding提供了三种Observable: Observable objects、Observable fields and Observable collections,分别表示观察对象、观察字段、观察集合,若相应的对象、字段、集合数据变化时候,那么将会自动更新UI。
这里直接使用ObservableBoolean,省去创建整个Observable object的繁琐。

    private ObservableBoolean isSelected;
    ...

    //set 之后,自动更新UI
    OnViewClickListener selectedListener = new OnViewClickListener() {

        @Override
        public void onClick(View v) {
            RecyclerItemViewBinding binding = DataBindingUtil.findBinding(v);
               VehicleInfo data = binding.getInfo();
               for(VehicleInfo e : getList()){
                   if(e.getIsSelected().get()) {
                       e.getIsSelected().set(false);
                       break;
                   }
               }
               data.getIsSelected().set(true);
        }
    };

源码

GitHub地址:AndroidDataBindingTutorial

发表评论

电子邮件地址不会被公开。 必填项已用*标注