Recyclerview
Recyclerview在App开发中十分常见,接下来就用kotlin来呈现recyclerview
一开始要先加入dependency
implementation "androidx.recyclerview:recyclerview:1.1.0"
// For control over item selection of both touch and mouse driven selection
implementation "androidx.recyclerview:recyclerview-selection:1.1.0-rc01"
xml(主画面)
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/recyclerview"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
这边在建立一个item_view的xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/item_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.92"
android:textSize="25dp"
android:id="@+id/textview" />
</LinearLayout>
再来是activity
val user :MutableList<Fruit> = mutableListOf()
user.add(Fruit("apple"))
user.add(Fruit("banana"))
user.add(Fruit("lemon"))
val recyclerView:RecyclerView = findViewById(R.id.recyclerview)
val recyclerAdapter = RecyclerAdapter(this,user)
recyclerView.adapter = recyclerAdapter
最後是adapter
class RecyclerAdapter(private val content:Context, private val mData:List<Fruit>):
RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
val inflater:LayoutInflater = LayoutInflater.from(content)
inner class ViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
val fruitname = itemView.findViewById<TextView>(R.id.textview)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerAdapter.ViewHolder {
val view= LayoutInflater.from(content).inflate(R.layout.item_view,parent,false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return mData.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
var currentData:Fruit = mData[position]
holder.fruitname.text = currentData.fruit
}
}
其实在不用databinding的情况下,kotlin的写法跟java其实是差不多的
成果如下
那昨天介绍完路由表,我们今天要来部署我们的路由器啦! 那笔者还是推荐大家使用这些系统来当作路由器。 ...
二维阵列的一维读入法 #include <math.h> #include <st...
今天我们来聊点轻松(?)的主题 - 「如何设计出自己的 RxJS Operators」吧! 为何要自...
前言 本篇是采用一个 MongoDB 结合 MongoExpress 应用当作范例 来实际操作布署 ...
Fake it till you make it(假装成功,直到你真的成功)。 - Emily i...