用kotlin写一个listview

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a243920187/article/details/82225442
package com.example.lenovo.myapplication

...不重要...
// import 自身layout
import kotlinx.android.synthetic.main.activity_list.*
// import adapter中用到的layout
import kotlinx.android.synthetic.main.item_recycler.view.*

class ListActivity : AppCompatActivity() {

    private var adapter: MyAdapter? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_list)
        initView()
    }

    fun initView() {
        adapter = MyAdapter(10)
        list_view.adapter = adapter


    }

    class MyAdapter(counts: Int) : BaseAdapter() {
        private val myCounts = counts

// converView 是可空参数,定义时需要有?
        @SuppressLint("ViewHolder")
        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
            var holder: MyView?
            var convertViews: View? = null
            when (convertView) {
                null -> {
                    println("查看view是否为空:$convertView")
                    convertViews = LayoutInflater.from(parent?.context).inflate(R.layout.item_recycler, null)
                    holder = MyView(convertViews.iv_icon, convertViews.tv_item_name, convertViews.tv_item_recycler)
                    // 设置参数时不再是“set参数名()“ 一律是".参数名"
                    convertViews.tag = holder
                }
                else -> {
                    println("查看view是否为空========:$convertView")
                    // 需要为自己定义的view设置值,否则会是null
                    convertViews = convertView
                    holder = convertViews!!.tag as MyView?
                }

            }
            holder!!.texts.setImageResource(R.mipmap.ic_launcher)
            holder!!.name.text="啦啦啦"
            holder!!.item.text="fssdfsd"
            return convertViews;
        }

        override fun getItem(position: Int): Any {
            return position
        }

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

        override fun getCount(): Int {
            return myCounts;
        }

        class MyView(var texts: ImageView, var name: TextView, var item: TextView)

    }
}


猜你喜欢

转载自blog.csdn.net/a243920187/article/details/82225442