Kotlin ListView设置Adapter

时间:2024-04-02 08:03:21

直接上代码。

1.附上Activity代码

package com.example.chehang168.kotlindemo

import android.view.View
import android.widget.AdapterView
import com.example.chehang168.kotlindemo.adapter.ListViewAdapter

//这里注入可以直接获取xml文件中的id.减少findViewById
import kotlinx.android.synthetic.main.activity_main.*

//自己封装的BaseActivity,你们可以忽略。直接继承Activity
class MainActivity : BaseActivity() {

    private var itemList = ArrayList<String>()
    private var adapter:ListViewAdapter? = null

    override fun createView(): Int {
        return R.layout.activity_main
    }

    override fun initView() {
        //模拟假数据
        getData()
        //构造器把参数传递到适配器中
        adapter = ListViewAdapter(this,itemList)
        //直接xml文件中id.adapter设置适配器》java中的listView.setAdapter(adapter);
        listView.adapter = adapter
        //设置listView点击监听
        listView.setOnItemClickListener {    
            adapterView: AdapterView<*>, view:View, i: Int, l: Long ->
            showShortToast(itemList[i])
        }
    }

    
    fun getData(){
        for(i in 0..20){
            itemList.add("数据>>>>>>>>>>"+i)
        }
    }

}

 

2.Adapter代码

package com.example.chehang168.kotlindemo.adapter

import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.example.chehang168.kotlindemo.MainActivity
import com.example.chehang168.kotlindemo.R

/**
 * @Author: shuaishuai
 * @Time: 2019/2/27 3:35 PM
 * @Description:适配器
 */
//构造器直接写在类后面
class ListViewAdapter(activity: MainActivity, itemList: ArrayList<String>) : BaseAdapter(){

    private var activity: Activity? = null
    private var itemList: ArrayList<String>? = null

    //初始化函数。类似于java中的构造器执行顺序
    init {
        this.activity = activity
        this.itemList = itemList
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var holder: TestViewHolder
        var view:View

        if(convertView==null){
            view = View.inflate(activity, R.layout.list_adapter,null)
            holder = TestViewHolder(view)
            view.tag = holder
        }else {
            view = convertView
            holder = view.tag as TestViewHolder
        }

        //直接.text来设置文本。类似与java中的 holder.textView.setText("文本");
        holder.str.text = itemList?.get(position) ?: ""

        return view
    }

    override fun getItem(position: Int): Any {
        return itemList?.get(position)!!
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getCount(): Int {
        return itemList?.size!!
    }


    class TestViewHolder(var view:View){
         var str:TextView = view.findViewById(R.id.textContent)
    }


}

Kotlin ListView设置AdapterKotlin ListView设置Adapter