使用 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