适配器
class MyAdapter(val content: Context, val list: List<String>) : BaseAdapter() { override fun getCount(): Int { return list.size } override fun getItem(p0: Int): Any { return list.get(p0) } override fun getItemId(p0: Int): Long { return p0.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { var view = convertView var hold:ViewHolder? if (view==null){ hold=ViewHolder() view=LayoutInflater.from(content).inflate(R.layout.activity_item,null) hold.str=view.findViewById(R.id.My_text) view.tag=hold }else{ hold=view.tag as ViewHolder } hold.str!!.text=list.get(position) return view!! } inner class ViewHolder{ var str: TextView? =null } }
主类调用
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initView() } private fun initView() { val My_listview = findViewById<ListView>(R.id.My_listview) var list = listOf("gu", "jack", "li", "fa") var myAdapter = MyAdapter(this, list) My_listview.adapter = myAdapter } }