Kotlin 第一个 app
使用 RecycleView 显示测试数据 显示结果
在activity_main.xml 添加对应控件布局 (TextView RecycleView)
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.administrator.kotlintapplication.MainActivity"> <TextView android:id="@+id/content" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintRight_toRightOf="parent" app:layout_constraintLeft_toLeftOf="parent" android:text="test"/> <android.support.v7.widget.RecyclerView android:id="@+id/recycler" app:layout_constraintTop_toBottomOf="@+id/content" android:layout_width="match_parent" android:layout_height="wrap_content"/> </android.support.constraint.ConstraintLayout>
item_text.xml (TextView)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal"> <TextView android:id="@+id/item_content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp"/> </LinearLayout>
MainActivity 相关代码
setContentView(R.layout.activity_main) content.text = "Hello_Kotlin" val list : MutableList<Test> = ArrayList()//创建一个可添加内容的List for (i in 1..30){//添加数据 list.add(Test("ff_" + i, "ff_hh_" + i)) } recycler.layoutManager = LinearLayoutManager(this)//设置RecycleView 的 LayoutManager val adapter = Adapter(this, list, { p, t -> Toast.makeText(this@MainActivity, "position= " + p + "\nname = " + t.n, Toast.LENGTH_SHORT).show() }) recycler.adapter = adapter
Adapter 相关代码
class Adapter(context: Context, list: List<Test>, val itemListener: (Int, Test) -> Unit) : RecyclerView.Adapter<Adapter.ViewHolder>() { private var context: Context? = context private var list: List<Test>? = list override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val convertView = LayoutInflater.from(context).inflate(R.layout.item_text, parent, false) return ViewHolder(convertView) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val t = list!![position] holder.textView.text = t.n holder.textView.setOnClickListener { itemListener(position, t) } } override fun getItemCount(): Int { return list!!.size } class ViewHolder(v: View) : RecyclerView.ViewHolder(v) { var textView: TextView = v.findViewById(R.id.item_content) } }
OnItemClickListener 接口
interface OnItemClickListener { fun onItemClick(position: Int, test: Test) }
Kotlin 创建类时会自动生成 对应的 get/set方法
如果只有一个构造函数数时书写方法如下:
Test 类
class Test (name: String, surName: String){ val n = name val sur = surName; }附带githup 链接地址 demo githup 地址
https://github.com/androidkf93/Kotlin.git
https://github.com/androidkf93/Kotlin.git