假设所有数据都可以按如下形式从数据库中加载:
部门:
data class Department(val id: Int, val title: String, val children: ArrayList<Item>)
项目:
data class Item(val id: Int, val title: String)
可以计算部门在列表中的位置。例如,第一个部门位于索引 0,第二个部门位于 departments.get(0).children.size + 1,依此类推。
完整代码:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val data = arrayListOf<Department>(
Department(0, "Department1",
arrayListOf(
Item(0, "Item1.1"),
Item(1, "Item1.2"),
Item(3, "Item1.3")
)),
Department(0, "Department2",
arrayListOf(
Item(0, "Item2.1")
)),
Department(0, "Department3",
arrayListOf(
Item(0, "Item3.1"),
Item(1, "Item3.2")
)),
Department(0, "Department4",
arrayListOf(
Item(0, "Item4.1"),
Item(1, "Item4.2"),
Item(1, "Item4.3")
))
)
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.adapter = Adapter(this, data)
}
}
class Adapter(val context: Context, val list: ArrayList<Department>): RecyclerView.Adapter<VH>() {
var total: Int = 0
var sectionIndices: ArrayList<Int> = arrayListOf()
var sectionSizes: ArrayList<Int> = arrayListOf()
init{
var index = 0
var pos = 0
for (d in list){
sectionIndices.add(pos)
sectionSizes.add(d.children.size)
pos += (1 + d.children.size)
index += 1
}
total = pos
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
val view = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false)
return VH(view)
}
override fun getItemCount(): Int {
return total
}
override fun onBindViewHolder(holder: VH, position: Int) {
for (section in 0 .. sectionIndices.size - 1){
if (position >= sectionIndices.get(section)
&& position <= sectionIndices.get(section) + sectionSizes.get(section)){
val i = position - sectionIndices.get(section)
when (i){
0 -> {
// department
val department = list.get(section)
holder.textView.typeface = Typeface.DEFAULT_BOLD
holder.textView.text = department.title
}
else -> {
// item
val item = list.get(section).children.get(i - 1)
holder.textView.typeface = Typeface.DEFAULT
holder.textView.text = item.title
}
}
break
}
}
}
}
class VH(val view: View): RecyclerView.ViewHolder(view){
val textView: TextView
init {
textView = view.findViewById(android.R.id.text1)
}
}
data class Department(val id: Int, val title: String, val children: ArrayList<Item>)
data class Item(val id: Int, val title: String)