如何在將清單項目 data 顯示在 RecyclerView
在MainActivity 呼叫 refresh ,將要顯示的data 寫入
class MainActivity : AppCompatActivity() {
adapter.refresh(
listOf(Todo("Allen", false), Todo("John", false))
)
}
使用 notifyDataSetChanged()) 告知 Adapter 更新 ListView 的方法
final void notifyDataSetChanged()
Notify any registered observers that the data set has changed.
class TodoAdapter : RecyclerView.Adapter<TodoViewHolder>() {
fun refresh(todos: List<Todo>) {
this.todos = todos
notifyDataSetChanged()
}
}
建立清單每個項目,載物件資料 data class:
data class Todo(
val name: String,
val checked: Boolean
)
每個項目 view.xml UI
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<androidx.appcompat.widget.AppCompatCheckBox
android:id="@+id/checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="name" />
</LinearLayout>
reference:https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.Adapter
reference:https://www.notion.so/RecyclerView-8-26-Andy-b0d303838fe0425a95d8ba2d4cf89727