Android中使用RecyclerView实现可折叠项的方法是使用ExpandableRecyclerView库。这个库提供了可折叠项的功能,非常适合需要展示大量嵌套数据的场景。
首先,需要在build.gradle文件中添加以下依赖项:
implementation 'com.github.bignerdranch:expandablerecyclerview:4.0.1-RC1'
接着,在布局文件中使用ExpandableRecyclerView代替RecyclerView。在adapter中,需要实现ExpandableRecyclerAdapter来处理可折叠项的展开和折叠。以下是一个adapter的例子:
class MyExpandableAdapter(private val itemList: List) :
ExpandableRecyclerAdapter(itemList) {
override fun onCreateParentViewHolder(parentViewType: Int, parentView: ViewGroup): RecyclerView.ViewHolder {
val view = LayoutInflater.from(parentView.context).inflate(R.layout.item_group, parentView, false)
return GroupViewHolder(view)
}
override fun onCreateChildViewHolder(childViewType: Int, childView: ViewGroup): RecyclerView.ViewHolder {
val view = LayoutInflater.from(childView.context).inflate(R.layout.item_child, childView, false)
return ChildViewHolder(view)
}
override fun onBindParentViewHolder(parentViewHolder: RecyclerView.ViewHolder, parentPosition: Int, item: ItemGroup) {
val groupViewHolder = parentViewHolder as GroupViewHolder
groupViewHolder.tvTitle.text = item.title
}
override fun onBindChildViewHolder(childViewHolder: RecyclerView.ViewHolder, parentPosition: Int, childPosition: Int, item: Item) {
val childViewHolder = childViewHolder as ChildViewHolder
childViewHolder.tvItemName.text = item.name
}
inner class GroupViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvTitle: TextView = itemView.findViewById(R.id.tvTitle)
}
inner class ChildViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvItemName: TextView = itemView.findViewById(R.id.tvItemName)
}
}
最后,将adapter设置给ExpandableRecyclerView即可。
val recyclerView = findViewById(R.id