转自郭神的《第一行代码》第3版
①自定义ListView每行的组件类(比如每行包含一张图片和一段文字)
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中新建ListView
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
③自定义适配器FruitAdapter,继承自ArrayAdapter,并将<泛型>指定为前面定义的类
class FruitAdapter(activity:Activity,val resourceId:Int,data:List<Fruit>):ArrayAdapter<Fruit>(activity,resourceId,data){
inner class ViewHolder(val fruitImage:ImageView,val fruitName:TextView)
override fun getView(position:Int,convertView:View?,parent:ViewGroup):View{
val view:View
val viewHolder:ViewHolder
if(convertView == null){
view = LayoutInflater.from(context).inflate(resourceId,parent,false)
val fruitImage:ImageView= view.findViewById(R.id.fruitImage)
val fruitName:TextView=view.findViewById(R.id.fruitName)
viewHolder = ViewHolder(fruitImage,fruitName)
view.tag=viewHolder
}else{
view=convertView
viewHolder=view.tag as ViewHolder
}
val fruit=getItem(position)
if(fruit != null){
viewHolder.fruitImage.setImageResource(fruit.imageId)
viewHolder.fruitName.text=fruit.name
}
return view
}
}
④在MainActivity中启动
class MainActivity : AppCompatActivity(){
private val fruitList=ArrayList<Fruit>()
override fun onCreate(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initFruits()
val adapter = FruitAdapter(this,R.layout.fruit_item,fruitList)
listView.adapter=adapter
}
private fun initFruits(){
repeat(2){
fruitList.add(Fruit("Apple",R.drawable.apple_pic))
fruitList.add(Fruit("Banana",R.drawable.Banana_pic))
}
}
}