📅  最后修改于: 2023-12-03 15:34:41.585000             🧑  作者: Mango
RecyclerView is a flexible and efficient version of ListView and GridView. It is used to display large sets of data in a list or grid.
LinearLayoutManager is a default layout manager used in RecyclerView. It arranges items in a vertical or horizontal linear layout. It is defined in the android.support.v7.widget.LinearLayoutManager package.
Kotlin is a modern, statically typed, cross-platform programming language. It is designed to be concise, safe, and interoperable with Java.
Add RecyclerView to your layout file. In this example, we will use a vertical LinearLayout.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/myRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Create an adapter that extends RecyclerView.Adapter. The adapter is responsible for creating and binding views for each item in the data set.
class MyAdapter(private val myData: List<String>): RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.my_item_layout, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(myData[position])
}
override fun getItemCount() = myData.size
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(item: String) {
itemView.findViewById<TextView>(R.id.textView).text = item
}
}
}
Create a LayoutManager that extends LinearLayoutManager. The LayoutManager is responsible for measuring and laying out views.
class MyLayoutManager(context: Context) : LinearLayoutManager(context) {
override fun canScrollVertically() = true
override fun canScrollHorizontally() = true
}
Set the LayoutManager to RecyclerView and create an instance of the adapter. Then, set the adapter to RecyclerView.
val myRecyclerView = findViewById<RecyclerView>(R.id.myRecyclerView)
myRecyclerView.layoutManager = MyLayoutManager(this)
val myData = listOf("Item 1", "Item 2", "Item 3")
myRecyclerView.adapter = MyAdapter(myData)
In this tutorial, we have shown how to use RecyclerView with LinearLayoutManager and Kotlin. RecyclerView can be used to display large sets of data in a list or grid, and LinearLayoutManager arranges items in a linear layout. Kotlin is a modern, concise, and safe programming language that can be used to develop Android applications.