我们如何在android中使用kotlin实现基础适配器?

时间:2017-09-11 08:53:10

标签: android kotlin android-adapter

我是kotlin编程语言的新手,如何在android中使用基础适配器在kotlin中实现列表视图。任何人都可以帮助我。

1 个答案:

答案 0 :(得分:10)

检查此代码

public class ListViewActivity() : AppCompatActivity() {

override fun onCreate(savedState: Bundle?) {
    super.onCreate(savedState)
    setContentView(R.layout.activity_list_view)

    val lv = findViewById(R.id.list) as ListView
    lv.adapter = ListExampleAdapter(this)
}

private class ListExampleAdapter(context: Context) : BaseAdapter() {
    internal var sList = arrayOf("Sunday", "Monday")
    private val mInflator: LayoutInflater

    init {
        this.mInflator = LayoutInflater.from(context)
    }

    override fun getCount(): Int {
        return sList.size
    }

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

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

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
        val view: View?
        val vh: ListRowHolder
        if (convertView == null) {
            view = this.mInflator.inflate(R.layout.list_row, parent, false)
            vh = ListRowHolder(view)
            view.tag = vh
        } else {
            view = convertView
            vh = view.tag as ListRowHolder
        }

        vh.label.text = sList[position]
        return view
    }
}

private class ListRowHolder(row: View?) {
    public val label: TextView

    init {
        this.label = row?.findViewById(R.id.label) as TextView
    }
}