Add two sections in recyclerview android

后端 未结 6 1089
天命终不由人
天命终不由人 2020-12-04 12:12

In my application i am using recyclerview to display all contact list. I want two section in recyclerview.

Like one section is my application contact list and second

6条回答
  •  猫巷女王i
    2020-12-04 13:10

    Alternative to using any third party library or using custom logic to add header to RecyclerView, there is a much simpler solution using Android SDK. You can simply use ExpandableListView. You might be thinking that it makes the list collapsible, but there is a very simple thing which you can do to avoid the same. In the adapter class for ExpandableListView, in the getGroupView method, simply add the following line:

    (parent as ExpandableListView).expandGroup(groupPosition)
    

    The method would look something like this:

    override fun getGroupView(groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup?): View {
        var view = convertView
        if (convertView == null) {
            val layoutInflater = context
                .getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater
            view = layoutInflater.inflate(R.layout.group_view, null)
        }
        /*
         Code to populate your data
         */
    
        // The following code will expand the group whenever the group view is inflated
        (parent as ExpandableListView).expandGroup(groupPosition)
        return view
    }
    

    This works simply due to the way how ExpandableListView adapter works. Whenever you try to collapse a group header, it calls the getGroupView method(so that you can inflate a different view for expanded/collapsed state). But you are expanding the group in that method, hence the view never actually collapses, effectively giving you a sectioned list appearance.

    Expect for the one line mentioned above, all other part of the same is exactly as you would do with a normal ExpandableListView, hence there is no additional bit of customisation you need to do.

提交回复
热议问题