接口和生成的绑定文件

时间:2017-03-16 01:35:01

标签: android data-binding interface android-databinding

我正在使用带有多个不同布局文件的RecyclerView进行数据绑定,但使用的是通用视图模型。有没有办法让生成的Binding文件实现一个通用接口来简化以下(工作但丑陋)的代码?

给定布局文件,例如:

R.layout.list_item_cat
R.layout.list_item_dog
R.layout.list_item_mouse

在ActionAdapter中:

    @Override
    public ActionAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        @LayoutRes int layoutToInflate;
        switch (viewType) {
            case 0:
                layoutToInflate = R.layout.list_item_cat;
                break;
            case 1:
                layoutToInflate = R.layout.list_item_dog;
                break;
            case 2:
                layoutToInflate = R.layout.list_item_mouse;
                break;
        }
        return new ViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), layoutToInflate, parent, false));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (holder.mBinding instanceof ListItemCatBinding) {
            ((ListItemCatBinding) holder.mBinding).setViewModel(mViewModelList.get(position));
        }
        else if (holder.mBinding instanceof ListItemDogBinding) {
            ((ListItemDogBinding) holder.mBinding).setViewModel(mViewModelList.get(position));
        }
        else if (holder.mBinding instanceof ListItemMouseBinding) {
            ((ListItemMouseBinding) holder.mBinding).setViewModel(mViewModelList.get(position));
        }

我知道上面的例子并不算太糟糕,但是能够操作一组Binding文件会很方便,这些文件可以共享常见的东西,而不必经常检查和转换它们的类型,特别是在更复杂的情况下

2 个答案:

答案 0 :(得分:3)

查看这篇文章:

https://medium.com/google-developers/android-data-binding-recyclerview-db7c40d9f0e4#.l6soxb3sd

您可以使用:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.mBinding.setVariable(BR.viewModel,  mViewModelList.get(position));
    holder.mBinding.executePendingBindings();
}

答案 1 :(得分:0)

您应该覆盖函数getViewType(int position)以获取要绑定数据的正确布局