kotlin中安卓listview实现

来源:互联网 发布:房地产数据网 编辑:程序博客网 时间:2024/06/09 16:56

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    }}

原创粉丝点击