Kelin-Hong / MVVMLight

A toolkit help to build Android MVVM Application
1.85k stars 333 forks source link

RecyclerView里面的Item使用复杂控件 #10

Closed SilverLin07 closed 6 years ago

SilverLin07 commented 7 years ago

你好,我在使用RecyclerView时,有部分的item需要使用复杂的控件,而这些控件无法写成在layout里面与ViewModel进行交互的形式,我考虑过使用DataBindingUtil来获取相关的Binding以获取其引用来进行操作但是,由于在RecyclerView使用

itemView.set(BR.viewModel, R.layout.listitem_home_title);

来进行绑定,因此我暂时无法获取到相应的Binding,我该如何获取到这个binding,希望你能帮我解决这个问题。 祝好!

Kelin-Hong commented 7 years ago

adapter.setViewHolderFactory(new ViewHolderFactory() { @Override public RecyclerView.ViewHolder createViewHolder(ViewDataBinding binding) { return new MyCustomViewHolder(binding.getRoot()); } }); 这个试试 😁

SilverLin07 commented 7 years ago

你是指放弃下面的写法

        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:itemView="@{viewModel.itemView}"
            app:items="@{viewModel.itemViewModels}"
            app:layoutManager="@{LayoutManagers.linear()}"/>

而在代码中使用adapter,并通过setAdapter的方式实现,然后通过对这个adapter获取到相应的binding么?

Kelin-Hong commented 7 years ago

你详细看下这个https://github.com/evant/binding-collection-adapter 看有什么办法吗?

SilverLin07 commented 7 years ago

谢谢你的回答,我利用https://github.com/markzhai/DataBindingAdapter 这个方法,通过重新设置adapter的方式解决了问题

ZhengJiao commented 7 years ago

ImagePipelineFactory was not initialized 你们有没有碰到这个问题

could-deng commented 6 years ago

@SilverLin07 你好,我也遇到了这个问题,请问你通过https://github.com/markzhai/DataBindingAdapter ,怎么重新设置adapter解决的,能细说一下吗,谢谢

SilverLin07 commented 6 years ago

@could-deng 具体你可以参考我给的链接里面的demo 简单说下,

//layout
<android.support.v7.widget.RecyclerView
                    android:id="@+id/recycler_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    app:adapter="@{adapter}"
                    app:layoutManager="@{LayoutManagers.linear()}"
                    app:layout_behavior="@string/appbar_scrolling_view_behavior"
                    app:onLoadMoreCommand="@{viewModel.onLoadMoreCommand}"/>

在layout里面设置adapter,然后实例化你需要的adapter,在viewModel里面把它设置进获取到的binding里面就行了,

//Activity或者fragment
binding = DataBindingUtil.inflate(inflater, R.layout.home, container, false);
mHomeViewModel = new HomeViewModel(this, binding);
binding.setViewModel(mHomeViewModel);
//ViewModel
mMultiTypeAdapter = new MultiTypeAdapter(mFragment.getContext());
        mMultiTypeAdapter.addViewTypeToLayoutMap(VIEW_TYPE_HEADER, R.layout.listitem_home_header);
        mMultiTypeAdapter.addViewTypeToLayoutMap(VIEW_TYPE_PRODUCTS, R.layout.listitem_home_products);
        mMultiTypeAdapter.addViewTypeToLayoutMap(VIEW_TYPE_TAIL, R.layout.listitem_home_tail);

mBinding.setAdapter(mMultiTypeAdapter);

这里我是完全放弃了

app:itemView="@{viewModel.itemView}"
app:items="@{viewModel.itemViewModels}"

这种写法的,使用了adapter