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.
如下图所示
MainItem布局如下:
<?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>
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
}
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)
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。