1. Introduction

If you need to display multiple layouts, most of the time, you can put all the layouts in one file and hide and show the controls. The obvious downside to doing this is that you have to do extra drawing, which affects performance. Also, if you want to show the error of the layout when the error how to write more elegant? To solve such problems, Groupie’s library appears.

2. Usage

2.1 Introducing external libraries

Add the following code to build.gradle to reference external libraries.

    implementation "Com. Xwray: groupie: 2.7.0."
    implementation "Com. Xwray: groupie - kotlin - android - extensions: 2.7.0"
    implementation "Com. Xwray: groupie - databinding: 2.7.0"
Copy the code

2.2 create BindableItem

As many viewTypes as we need, we need to create as many BindableItems.

data class ListBindableItem(
    val str: String,
    val onClick: (String) -> Unit
) : BindableItem<ItemListBinding>() {
    // Returns a layout Int
    override fun getLayout(a): Int {
        return R.layout.item_list
    }
    // Bind data
    override fun bind(viewBinding: ItemListBinding, position: Int) {
        viewBinding.textview.text = str
        viewBinding.textview.setOnClickListener { onClick(str) }
    }
}
Copy the code

2.3 Creating an array of sections to display

Create a List

, and then pass in the data you want to display to the BindableItem, and then create it and pass it to the Section.

    private fun generateData(a): List<Section> {
        val prefix = "MOON"
        val result: ArrayList<Section> = arrayListOf()
        for (i in 0.40.) {
            val section = Section().apply {
                if (i % 2= =0) {
                    add(ListBindableItem(prefix + i, onClick))
                } else {
                    add(ListTwoBindableItem(prefix + i, onClick))
                }
            }
            result.add(section)
        }
        return result
    }
Copy the code

2.4 Create Adapter and update Section

Traditionally, we create ListAdapter and so on, but here we need to create the GroupAdapter provided by Groupie. The List

data is then updated using the groupeAdapter.update method.

private val adapter: GroupAdapter<GroupieViewHolder> = GroupAdapter()
binding.recyclerview.adapter = adapter
val sections = generateData()
adapter.update(sections)
Copy the code

3. The evaluation

To address the pain point of being able to display multiple different viewtypes in a RecyclerView, Google introduced MergeAdapter.

Groupie has the advantage of mixing viewTypes with MergeAdapter, but MergeAdapter does not.

MergeAdapter can only display the first ViewType before displaying the second ViewType.

Of course, MergeAdapter has the advantage of being elegant and easy to read.

4. Github

MergeAdapter tutorials: juejin.cn/post/684490…

Android ConstraintLayout: juejin.cn/post/684490…

Making: github.com/HyejeanMOON…