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

如何用Groupie库实现Kotlin中Expandable RecyclerView单组展开

使用Groupie实现Expandable RecyclerView单组展开功能

要实现同一时间仅展开一个组的需求,核心是记录当前展开的组实例,点击新组时先收起旧组再展开新组,具体实现步骤如下:

  1. 维护当前展开组的引用
    在你的Adapter、Activity或Fragment中声明变量,保存当前处于展开状态的组:

    private var currentExpandedGroup: ExpandableGroup? = null
    
  2. 自定义组点击处理逻辑
    替换默认的onToggleExpanded()调用,改为以下逻辑确保单组展开:

    private fun handleGroupClick(targetGroup: ExpandableGroup) {
        when {
            // 当前点击的组已展开:直接收起
            targetGroup.isExpanded -> {
                targetGroup.toggleExpanded()
                currentExpandedGroup = null
            }
            // 存在已展开的其他组:先收起旧组,再展开新组
            currentExpandedGroup != null -> {
                currentExpandedGroup?.toggleExpanded()
                notifyItemChanged(groups.indexOf(currentExpandedGroup))
                
                targetGroup.toggleExpanded()
                currentExpandedGroup = targetGroup
            }
            // 无已展开组:直接展开当前组
            else -> {
                targetGroup.toggleExpanded()
                currentExpandedGroup = targetGroup
            }
        }
        // 更新当前点击组的UI状态
        notifyItemChanged(groups.indexOf(targetGroup))
    }
    
  3. 绑定点击事件到自定义逻辑
    在RecyclerView的点击监听中调用上述方法,替代默认的展开逻辑:

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_group_layout, parent, false)
        return GroupViewHolder(view).apply {
            itemView.setOnClickListener {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    val group = groups[position] as ExpandableGroup
                    handleGroupClick(group)
                }
            }
        }
    }
    

注意事项

  • 如果使用自定义ExpandableGroup子类,确保toggleExpanded()能正确修改组的展开状态。
  • 调用notifyItemChanged()是为了让RecyclerView及时更新组的UI(比如展开/收起箭头图标)。

内容的提问来源于stack exchange,提问作者AMAL JO VARGHESE

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 08:25:01