RecyclerView 可以輕鬆高效地顯示大量數據。
RecyclerView回收這些單獨的元素。當一個項目滾出屏幕時, RecyclerView 不會破壞它的視圖。
RecyclerView 的步驟
build.gradle(app)
dependencies {
implementation "androidx.recyclerview:recyclerview:1.2.1"
}
adapter and view holder
class Day19Adapter(private val dataSet: List<String>) :
RecyclerView.Adapter<Day19Adapter.ViewHolder>() {
/**
* Provide a reference to the type of views that you are using
* (custom ViewHolder).
*/
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val dataView: TextView
init {
dataView = view.findViewById(R.id.textView4)
}
}
// Create new views (invoked by the layout manager)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
// Create a new view, which defines the UI of the list item
val v = LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
return ViewHolder(v)
}
// Replace the contents of a view (invoked by the layout manager)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// Get element from your dataset at this position and replace the
// contents of the view with that element
holder.dataView.text = dataSet[position]
holder.itemView.setOnClickListener {
Toast.makeText(it.context, "第 $position 項被按下", Toast.LENGTH_SHORT).show() }
}
// Return the size of your dataset (invoked by the layout manager)
override fun getItemCount(): Int {
return dataSet.size
}
}
item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="50dp">
<ImageView
android:id="@+id/imgV"
android:layout_width="40dp"
android:layout_height="40dp"
app:srcCompat="@drawable/logo"
android:layout_margin="5dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_gravity="center"/>
<TextView
android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_marginStart="16dp"
android:layout_toEndOf="@+id/imgV"
android:text="GDG Taipei"
android:gravity="center_vertical"
android:textSize="24sp"/>
</RelativeLayout>
Activity:
val listData = ArrayList<String>()
for (i in 0..19) {
listData.add(i.toString())
}
val layoutManager = LinearLayoutManager(this)
layoutManager.orientation = LinearLayoutManager.VERTICAL
val dataList = findViewById<RecyclerView>(R.id.recyclerView)
dataList.layoutManager = layoutManager
dataList.adapter = Day19Adapter(listData)
執行結果:
https://developer.android.com/guide/topics/ui/layout/recyclerview