1. 程式人生 > >kotlin中安卓listview實現

kotlin中安卓listview實現

Kotlin最近一段時間火啦起來,我想自己學習學習,這是我自己簡單在as上寫的程式碼,與大家分享

首先佈局還是xml的形式

<?xml version="1.0" encoding="utf-8"?>
<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="com.rxd.trykotlin.MainActivity"> <android.support.v7.widget.ListViewCompat android:id="@+id/recycle" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v7.widget.ListViewCompat> </RelativeLayout>

但是,MainActivity.kt中寫的行駛略有不同

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val mListView=findViewById(R.id.recycle)as ListView
    mListView.adapter=ForcastAdapter(items,this)
}
自定義介面卡,其中注意構造引數前加val
class ForcastAdapter(val stringList
: List<String>,val mContext:Context) : BaseAdapter() { override fun getItem(position: Int): Any { return stringList[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun getCount(): Int { return stringList.size } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val view=LayoutInflater.from(mContext).inflate(R.layout.item_forcast,parent,false) val text= view.findViewById(R.id.tv_iteforcast) as TextView text.text=stringList[position] return view } }