evant / binding-collection-adapter

Easy way to bind collections to listviews and recyclerviews with the new Android Data Binding framework
Apache License 2.0
1.92k stars 255 forks source link

PageView + RecyclerView #87

Closed genaku closed 6 years ago

genaku commented 7 years ago

I can't catch how to implement PageView with some layout on pages (for example LinearLayout with TextView + RecyclerView inside). Could you please give example or inlcude it into sample app?

soitiroseta commented 6 years ago

first your page_layout:

<data>
      <variable name="sectionViewModel" type=".SectionViewModel"/>
</data>

<android.support.v4.view.ViewPager
      android:id="@+id/pager"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_below="@id/tab_layout"
      app:items="@{sectionViewModel.items}"
      app:itemBinding="@{sectionViewModel.itemBinding}"
      app:pageTitles="@{sectionViewModel.pageTitles}"/>

in your SectionViewModel

val items: ObservableList<CollectionModel> = ObservableArrayList()

val pageTitles = BindingViewPagerAdapter.PageTitles<CollectionModel> {
      position, item -> item.title
}

val itemBinding = ItemBinding.of<CollectionModel\> { itemBinding, position, item -\>
      itemBinding.set(BR.collection, R.layout.item_paged_list)
      itemBinding.bindExtra(BR.collectionViewModel,
                  viewModelProvider.get(CollectionViewModel.key(item.id), CollectionViewModel::class.java))
      itemBinding.bindExtra(BR.collection, item)
}.layoutRes(R.layout.item_paged_list)

in your list_layout:

<data>
      <import type="me.tatarka.bindingcollectionadapter2.LayoutManagers" />
      <variable name="collectionViewModel" type=".CollectionViewModel"/>
      <variable name="item" type="db.ItemCollection"/>
</data>

<android.support.v7.widget.RecyclerView
      android:id="@+id/list"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layoutManager="@{LayoutManagers.linear()}"
      app:items="@{collectionViewModel.items}"
      app:itemBinding="@{collectionViewModel.itemBinding}"/>

in your CollectionViewModel

val items: ObservableList<ItemCollection> = ObservableArrayList()

val itemBinding = ItemBinding.of<ItemCollection> { itemBinding, position, item ->
      temBinding.set(BR.item, R.layout.item_list)
      temBinding.bindExtra(BR.collectionViewModel,
                  viewModelProvider.get(ItemViewModel.key(item.id), ItemViewModel::class.java))
      itemBinding.bindExtra(BR.item, item)
}.layoutRes(R.layout.item_list)
dakuenjery commented 6 years ago

Where can I get viewModelProvider? Did you test this code?

soitiroseta commented 6 years ago

@dakuenjery, for get viewModelProvider i use Dagger2 with ViewModelProvider.Factory