转自郭神的《第一行代码》第3版
①自定义RecyclerView的组件类(比如包含一张图片和一段文字)
class Fruit(val name:String,val imageId:Int)
②新建组件的布局文件fruit_item.xml
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp">
<ImageView
android:id="@+id/fruitImage"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"/>
<TextView
android:id="@+id/fruitName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"/>
</LinearLayout>
在Activity布局文件activity_main.xml中新建RecyclerView将其放入界面中
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
③自定义适配器FruitAdapter,继承自RecyclerView.Adapter,并将<泛型>指定为在FruitAdapter中定义的内部类<FruitAdapter.ViewHolder>
执行顺序:onCreateViewHolder(找到布局)→MyViewHolder(找到组件) →onBindViewHolder(绑定数据)
class FruitAdapter(val fruitList:List<Fruit>):RecyclerView.Adapter<FruitAdapter.ViewHolder>(){
inner class ViewHolder(view:View):RecyclerView.ViewHolder(view){
val fruitImage:ImageView=view.findViewById(R.id.fruitImage)
val fruitName:TextView=view.findViewById(R.id.fruitName)
}
override fun onCreateViewHolder(parent:ViewGroup,viewType:Int):ViewHolder{
val view=LayoutInflater.from(parent).inflate(R.layout.fruit_item,parent,false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder:ViewHolder,position:Int){
val fruit=fruitList[position]
holder.fruitImage.setImageResource(fruit.imageId)
holder.fruitName.text=fruit.name
}
override fun getItemCount() = fruitList.size
}
④在MainActivity中启动
class MainActivity:AppCompatActivity(){
private val fruitList = ArrayList<Fruit>()
override fun onCreate(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentLayout(R.layout.activity_main)
initFruits()
val layoutManager=LinearLayoutManager(this)
recyclerView.layoutManager=layoutManager
val adapter=FruitAdapter(fruitList)
recyclerView.adapter=adapter
}
private fun initFruits(){
repeat(2){
fruitList.add(Fruit("Apple",R.drawable.apple_pic))
fruitList.add(Fruit("Banana",R.drawable.Banana_pic))
}
}
}