官方介绍
RecyclerView是ListView的一个更高级、更灵活的版本。RecyclerView组件是为大量的视图组件提供的一种容器,使得它们可以有效的在其中循环和滚动。 RecyclerView is a more advanced and flexible version of ListView. This widget is a container for large sets of views that can be recycled and scrolled very efficiently. Use the RecyclerView widget when you have lists with elements that change dynamically.
RecyclerView的使用
最终要达到的效果
如下图所示
编写相关的布局文件
MainItem布局如下:
代码语言:html复制<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="120dp"
android:orientation="vertical">
<ImageView
android:id="@ id/itemIcon"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="0.7"
tools:ignore="ContentDescription"
tools:srcCompat="@tools:sample/avatars" />
<TextView
android:textSize="20sp"
android:id="@ id/itemName"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.3"
android:gravity="center" />
</LinearLayout>
实现继承自RecyclerView.Adapter的Adapter类
代码语言:java复制class MainItemAdapter(private val itemList: List<MainItem>) :
RecyclerView.Adapter<MainItemAdapter.ViewHolder>() {
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val itemName: TextView = view.findViewById(R.id.itemName)
val itemIcon: ImageView = view.findViewById(R.id.itemIcon)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val ctx = parent.context
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.main_item, parent, false)
return ViewHolder(view).apply {
itemView.setOnClickListener {
val position = this.adapterPosition
val mainItem = itemList[position]
when (mainItem.id) {
1 -> {
ctx.startActivity(Intent(ctx, SenderActivity::class.java))
}
}
}
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val mainItem = itemList[position]
holder.itemName.text = mainItem.name
holder.itemIcon.setImageResource(mainItem.iconId)
}
override fun getItemCount(): Int = itemList.size
}
在Activity中初始化数据和RecyclerView
代码语言:java复制private val itemList = ArrayList<MainItem>()
private fun initItems() {
repeat(20) {
itemList.addAll(
listOf(
MainItem(1, "Activity演示", R.drawable.activity_icon)
)
)
}
}
private fun initRecyclerView() {
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
recyclerView.layoutManager = GridLayoutManager(this, 3)
recyclerView.adapter = MainItemAdapter(itemList)
}