如何用Groupie库实现Kotlin中Expandable RecyclerView单组展开
使用Groupie实现Expandable RecyclerView单组展开功能
要实现同一时间仅展开一个组的需求,核心是记录当前展开的组实例,点击新组时先收起旧组再展开新组,具体实现步骤如下:
维护当前展开组的引用
在你的Adapter、Activity或Fragment中声明变量,保存当前处于展开状态的组:private var currentExpandedGroup: ExpandableGroup? = null自定义组点击处理逻辑
替换默认的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)) }绑定点击事件到自定义逻辑
在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
相关产品推荐
相关产品推荐

