RecyclerView 有多個不同的樣式的View ,稱為 multiple view type
使用 data class 改成可支援多種情境 sealed class
sealed class Todo(val viewType: Int) {
data class Title(val text: String) : Todo(TYPE_TITLE)
data class Item(
val name: String,
val checked: Boolean
) : Todo(TYPE_ITEM)
companion object {
const val TYPE_TITLE = 0
const val TYPE_ITEM = 1
}
}
Adapter 改成使用 RecyclerView.ViewHolder
class TodoAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var todos = listOf<Todo>()
//依 position 取得 view type
override fun getItemViewType(position: Int): Int {
return todos[position].viewType
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
// 依 viewType 呼叫 ViewHolder
return when (viewType) {
Todo.TYPE_TITLE -> TodoTitleViewHolder(parent)
else -> TodoViewHolder(parent)
}
}
override fun getItemCount(): Int {
return todos.size
}
//依 position 取得 view type 來綁定 ViewHolder
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (val todo = todos[position]) {
is Todo.Title -> (holder as TodoTitleViewHolder).bind(todo)
is Todo.Item -> (holder as TodoViewHolder).bind(todo)
}
}
fun refresh(todos: List<Todo>) {
this.todos = todos
notifyDataSetChanged()
}
}
最後呼叫adapter refresh 更新 RecyclerView data
val adapter = TodoAdapter()
recyclerView.adapter = adapter
.......
adapter.refresh(
listOf(
Todo.Title("聯絡人1"),
Todo.Item( "Allen",false),
Todo.Item("Bear", false)
Todo.Item("Mary", false),
Todo.Item("Sandy", false),
Todo.Title("聯絡人2"),
Todo.Item("Ray", false),
Todo.Item("Vic", false)
)
)
reference:https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.ViewHolder
reference:https://www.notion.so/RecyclerView-8-26-Andy-b0d303838fe0425a95d8ba2d4cf89727