Kotlin:編寫Android介面卡(Adapter)
阿新 • • 發佈:2019-01-02
說好今天要寫一個使用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<String>, 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
}
}
先寫成這樣吧,有什麼不懂的請在評論區留言,我能幫你解決的我會盡力的。