You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过单按钮点击展开可展开RecyclerView的所有父项?

一键展开RecyclerView所有可展开父项的实现

现有展开/折叠单个父项的代码如下:

private fun expandParentRow(position: Int){ // 展开单个项
    val currentBoardingRow = list[position]
    val services = currentBoardingRow.gameDetes
    currentBoardingRow.isExpanded = true
    var nextPosition = position
    if(currentBoardingRow.type == Constants.PARENT) {
        services?.forEach { service ->
            val parentModel = IndividualReport()
            parentModel.type = Constants.CHILD
            val subList: ArrayList<GameDete> = ArrayList()
            subList.add(service)
            parentModel.gameDetes = subList
            list.add(++nextPosition, parentModel)
        }
        notifyDataSetChanged()
    }
}

private fun collapseParentRow(position: Int){ // 折叠单个项
    val currentBoardingRow = list[position]
    val services = currentBoardingRow.gameDetes
    list[position].isExpanded = false
    if(list[position].type==Constants.PARENT){
        services?.forEach { _ ->
            list.removeAt(position + 1)
        }
        notifyDataSetChanged()
    }
}

核心问题与解决思路

批量展开时不能直接正序遍历父项——因为每次展开会往列表插入子项,导致后续父项的位置偏移,原来的索引会失效。最稳妥的方式是倒序遍历所有未展开的父项,从最后一个父项开始处理,前面的父项索引不会被后续操作影响。

批量展开实现代码

添加以下方法即可:

private fun expandAllParentRows() {
    // 收集所有未展开的父项位置
    val parentPositions = mutableListOf<Int>()
    list.forEachIndexed { index, item ->
        if (item.type == Constants.PARENT && !item.isExpanded) {
            parentPositions.add(index)
        }
    }
    // 倒序遍历调用单个展开方法
    parentPositions.reversed().forEach { position ->
        expandParentRow(position)
    }
}

绑定按钮点击事件

在你的展开按钮点击回调中调用这个方法:

expandAllButton.setOnClickListener {
    expandAllParentRows()
}

补充:批量折叠所有父项

逻辑和展开一致,同样用倒序遍历避免索引问题:

private fun collapseAllParentRows() {
    val parentPositions = mutableListOf<Int>()
    list.forEachIndexed { index, item ->
        if (item.type == Constants.PARENT && item.isExpanded) {
            parentPositions.add(index)
        }
    }
    parentPositions.reversed().forEach { position ->
        collapseParentRow(position)
    }
}

内容的提问来源于stack exchange,提问作者shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:00:57