RecyclerView 是 ListView 的進階版本。列表中的view 通過擴展 RecyclerView.ViewHolder class 來實作,data 與view 之間通過 RecyclerView.Adapter class 建立與配置,onBindViewHolder() 方法 將view綁定到對應data,此方法使用畫面position來顯示內容。
本篇先以 adapter 和 layout manager (linear / grid / staggered) 與 view holder 說明。
使用 RecyclerView 先import
dependencies {
implementation "androidx.recyclerview:recyclerview:1.1.0"
}
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/textTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="@string/todo_list_title"
android:textColor="#000"
android:textSize="26sp"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
class TodoViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_todo, parent, false)
) {
val checkbox: AppCompatCheckBox = itemView.checkbox
}
Adapter 介接 data 跟 View 的地方
class TodoAdapter : RecyclerView.Adapter<TodoViewHolder>() {
private var todos = listOf<Todo>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {
return TodoViewHolder(parent)
}
// 回傳 Adapter 包含幾筆資料
override fun getItemCount(): Int {
return todos.size
}
// 依據 position 正確的資料跟 ViewHolder 綁定
override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
val todo = todos[position]
holder.checkbox.text = todo.memo
holder.checkbox.isChecked = todo.checked
}
}
manager :linear / grid / staggered
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val adapter = TodoAdapter()
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
adapter.refresh(
listOf(Todo("hello", false), Todo("world", false))
)
}
}
LinearLayoutManager
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
GridLayoutManager
recyclerView.layoutManager = GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false)
StaggeredGridLayoutManager
recyclerView.layoutManager = StaggeredGridLayoutManager( 3, GridLayoutManager.VERTICAL)
reference: https://www.notion.so/RecyclerView-8-26-Andy-b0d303838fe0425a95d8ba2d4cf89727
reference :https://ithelp.ithome.com.tw/articles/10220196
reference :https://developer.android.com/guide/topics/ui/layout/recyclerview