主界面
class tooActivity : AppCompatActivity() {
private lateinit var tooBinding: ActivityTooBinding
private var fruitList:ArrayList<Fruit> = ArrayList<Fruit>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
tooBinding = ActivityTooBinding.inflate(layoutInflater)
setContentView(tooBinding.root)
//初始化数据
dataInit()
//创建适配器
val fruitAdapter = FruitAdapter(this,R.layout.lv_fruit_container_layou,fruitList)
tooBinding.lvFruitContainer.adapter = fruitAdapter
//点击事件
tooBinding.lvFruitContainer.setOnItemClickListener{
parent, view, position, id->
val fruit = fruitList[position]
Toast.makeText(this,fruit.name,Toast.LENGTH_LONG).show()
}
}
private fun dataInit(){
repeat(5){
fruitList.add(Fruit("apple",R.mipmap.ic_launcher))
fruitList.add(Fruit("banana",R.mipmap.ic_launcher))
fruitList.add(Fruit("orange",R.mipmap.ic_launcher))
}
}
}
适配器
class FruitAdapter(activity:Activity,val resLayoutId:Int,fruitList:ArrayList<Fruit>):ArrayAdapter<Fruit>(activity,resLayoutId,fruitList) {
private lateinit var view:View
private lateinit var viewHolder:ViewHolder
inner class ViewHolder(val fruitImg:ImageView,val fruitTitleContent:TextView)
@SuppressLint("ViewHolder")
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
//填充视图
if(convertView == null){
view = LayoutInflater.from(context).inflate(resLayoutId,parent,false)
val fruitImg = view.findViewById<ImageView>(R.id.img_fruit)
val fruitTitleContent = view.findViewById<TextView>(R.id.tv_fruit_title_content)
viewHolder = ViewHolder(fruitImg,fruitTitleContent)
view.tag = viewHolder
}else{
view = convertView
viewHolder = view.tag as ViewHolder
}
//拿到数据
val fruit = getItem(position)
//填充数据
if (fruit != null) {
viewHolder.fruitImg.setImageResource(fruit.ImageId)
viewHolder.fruitTitleContent.text = fruit.name
}
return view
}
}
item布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/img_fruit"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="@mipmap/ic_launcher"
/>
<TextView
android:id="@+id/tv_fruit_title_content"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:text="123"
android:textSize="25sp"
/>
</LinearLayout>