Implement multiple ViewHolder types in RecycleView adapter

后端 未结 9 1667
迷失自我
迷失自我 2020-12-13 16:34

It\'s maybe a discussion not a question.

Normal way to implement multiple types

As you know, if we want to implement multiple types in RecyclerView

9条回答
  •  时光说笑
    2020-12-13 16:48

    I use this approach intensively: http://frogermcs.github.io/inject-everything-viewholder-and-dagger-2-example/ In short:

    1. Inject map of view holder factories into adapter.
    2. Delegate onCreateViewHolder to injected factories.
    3. Define onBind on similar on base view holder so that you can call it with retrieved data in onBindViewHolder.
    4. Choose factory depending on getItemViewType (by either instanceOf or comparing field value).

    Why?

    It cleanly separates every view holder from the rest of app. If you use autofactory from google, you can easily inject dependencies required for every view holder. If you need to notify parent of some event, just create new interface, implement it in parent view (activity) and expose it in dagger. (pro tip: instead of initialising factories from their providers, simply specify that each required item's factory depends on factory that autofactory gives you and dagger will provide that for you).

    We use it for +15 view holders and adapter has only to grow by ~3 lines for each new added (getItemViewType checks).

提交回复
热议问题