Kotlin:编写Android适配器(Adapter)

说好今天要写一个使用Kotlin写Adapter的列子,我想了半天也没有组织好语言,直接上代码吧,有一定Android基础的小伙伴肯定是能看的懂的

package com.example.administrator.kotlintest

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView

/**
 * Created by zhanglei on 2017/5/31.
 * ListView的适配器
 */
class MyAdapter(var mList: List, var context: Context) : BaseAdapter() {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var holder: MyViewHolder
        //重用view
        var v: View
        if (convertView == null) {
            holder = MyViewHolder()
            v = LayoutInflater.from(context).inflate(R.layout.list_item_layout, parent, false)
            holder.textView = v.findViewById(R.id.list_text_item) as TextView
            //设置tag
            v.tag = holder
        } else {
            v = convertView
            //获取tag并强转
            holder = v.tag as MyViewHolder
        }

        //为TextView设置内容
        holder.textView.text = mList[position]
        return v
    }

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

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

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

    class MyViewHolder {

        lateinit var textView: TextView

    }
}

先写成这样吧,有什么不懂的请在评论区留言,我能帮你解决的我会尽力的。

你可能感兴趣的:(知识备忘录)