recyclerview在Fragment里面使用完整示例
时间: 2024-03-10 15:49:30 浏览: 179
好的,以下是一个在Fragment中使用RecyclerView的完整示例:
1. 首先,在你的布局文件中添加一个RecyclerView:
```xml
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 然后,在你的Fragment中初始化RecyclerView和Adapter:
```kotlin
class MyFragment : Fragment() {
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: MyAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_my, container, false)
recyclerView = view.findViewById(R.id.recycler_view)
adapter = MyAdapter()
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(context)
return view
}
// ...
}
```
3. 接下来,实现RecyclerView的Adapter,例如:
```kotlin
class MyAdapter : RecyclerView.Adapter<MyViewHolder>() {
private val data = listOf("Item 1", "Item 2", "Item 3")
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_my, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(data[position])
}
override fun getItemCount(): Int = data.size
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val textView: TextView = itemView.findViewById(R.id.text_view)
fun bind(text: String) {
textView.text = text
}
}
```
4. 最后,创建一个RecyclerView的item布局,例如:
```xml
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="18sp" />
```
这样就可以在Fragment中使用RecyclerView了,当然你还可以根据自己的需求对RecyclerView进行更多的定制和优化。
阅读全文