首先创建一个activity_main布局的文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
listview 每个item布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/str"/>
</LinearLayout>
listview适配器
package com.xz.myapplication
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import java.util.*
/**
* Created by Administrator on 2015/10/29 0029.
*/
class TestAdapter(val list: ArrayList<String>, val context: Context) : BaseAdapter() {
override fun getCount(): Int {
return list.size
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
var holder: TestViewHolder
var v: View
if (convertView == null) {
v = View.inflate(context, R.layout.item, null)
holder = TestViewHolder(v)
v.tag = holder
} else {
v = convertView
holder = v.tag as TestViewHolder
}
holder.str.text = list[position]
return v
}
override fun getItem(position: Int): Any? {
return list.get(position)
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
}
class TestViewHolder(var viewItem: View) {
var str: TextView = viewItem.findViewById(R.id.str) as TextView
}
创建一个TestActivity.kt的文件
package com.xz.myapplication
import android.app.Activity
import android.os.Bundle
import kotlinx.android.synthetic.activity_main.*
import java.util.*
public class TestActivity: Activity(){
private var itemList=ArrayList<String>()
private var adapter :TestAdapter?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
itemList.getData()
adapter = TestAdapter(itemList,this)
/*
此处listview控件是通过kotlinx.android.synthetic.activity_main.*获得
*/
listView.adapter = adapter
}
fun ArrayList<String>.getData(){
for(i in 0..20){
this.add("str:"+i)
}
}
}