kiotlin學習實現listview列表
阿新 • • 發佈:2018-11-02
介面卡
class MyAdapter(context: Context, list: ArrayList<String>) : BaseAdapter() { var list: ArrayList<String>? = null var context: Context? = null init { this.context=context this.list=list } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { var view: View var viewHolder: ViewHolder if (convertView == null) { view = View.inflate(context, R.layout.kotlin_lv_layout, null) viewHolder = ViewHolder() viewHolder.tv = view.findViewById(R.id.tv) view.tag = viewHolder } else { view = convertView viewHolder = view.tag as ViewHolder } viewHolder.tv!!.text = list!!.get(position) return view } override fun getItem(position: Int): Any { return list!!.get(position) } override fun getItemId(position: Int): Long { return 0 } override fun getCount(): Int { return list?.size ?: 0 } class ViewHolder { var tv: TextView? = null } }
設定介面卡
var list = ArrayList<String>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) data() list_view.adapter = MyAdapter(this, list) list_view.setOnItemClickListener(this) } fun data() { for (i in 0..20) { list.add("kotlin") } }