Android学习笔记03

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其实是差不多的
成果如下
https://ithelp.ithome.com.tw/upload/images/20210908/20141607dQHcsuSVJw.jpg


<<:  Day8 区块元素与行内元素

>>:  day8 : logging集中(中)

Day 4 - 部署 Home Lab 网路 - 安装路由器

那昨天介绍完路由表,我们今天要来部署我们的路由器啦! 那笔者还是推荐大家使用这些系统来当作路由器。 ...

【资料结构】读档相关 12/18更

二维阵列的一维读入法 #include <math.h> #include <st...

如何设计自己的 RxJS Operators

今天我们来聊点轻松(?)的主题 - 「如何设计出自己的 RxJS Operators」吧! 为何要自...

IT 铁人赛 k8s 入门30天 -- day8 Demo Project: MongoDB and MongoExpress

前言 本篇是采用一个 MongoDB 结合 MongoExpress 应用当作范例 来实际操作布署 ...

一次一件事就好,对你而言最重要的东西是什麽?

Fake it till you make it(假装成功,直到你真的成功)。 - Emily i...