kotlin RecyclerView用法(2列显示)
时间: 2023-11-16 07:01:52 浏览: 243
以下是使用Kotlin在RecyclerView中显示2列的步骤:
1. 在XML布局文件中添加RecyclerView控件:
```xml
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 创建一个RecyclerView的Adapter类,继承自RecyclerView.Adapter,并实现ViewHolder类:
```kotlin
class MyAdapter(private val data: List<String>) :
RecyclerView.Adapter<MyAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(data[position])
}
override fun getItemCount(): Int {
return data.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(item: String) {
itemView.itemTextView.text = item
}
}
}
```
3. 创建一个布局文件来表示RecyclerView中的每个项(item_layout.xml):
```xml
<TextView
android:id="@+id/itemTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp" />
```
4. 在MainActivity中初始化RecyclerView控件,并设置LayoutManager和Adapter:
```kotlin
class MainActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = GridLayoutManager(this, 2)
recyclerView.adapter = MyAdapter(listOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5"))
}
}
```
在这里,我们使用GridLayoutManager来实现2列布局。我们还创建了一个字符串列表来展示在RecyclerView中。
这样就完成了RecyclerView的2列显示。
阅读全文