RecyclerView的用法(示例)
作者:互联网
1添加依赖
implementation 'androidx.recyclerview:recyclerview:1.1.0'
2 添加布局xml文件
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_View"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
3 添加item的xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="90dp">
<TextView
android:id="@+id/time"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginTop="23dp"
android:layout_marginLeft="90dp"
android:text="2021-7-7"
android:textSize="35dp"/>
<TextView
android:id="@+id/detail"
android:layout_width="110dp"
android:layout_height="60dp"
android:layout_marginLeft="250dp"
android:layout_marginTop="20dp"
android:text="80.0"
android:textSize="40dp"/>
<TextView
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_marginLeft="340dp"
android:layout_marginTop="20dp"
android:text="KG"
android:textSize="40dp"/>
</FrameLayout>
</LinearLayout>
4 添加数据实例
open class weightData(
val weight: Double,
val time: String
)
5 MainActivity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
private val list = listOf(
weightData(25.0, "2020-7-1", 22.0),
weightData(23.0, "2020-7-2", 22.0),
weightData(22.0, "2020-7-3", 22.0),
weightData(21.0, "2020-7-4", 22.0)
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView: RecyclerView = findViewById(R.id.recycler_View)
//线性布局
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = WeightAdapter(list)
}
class WeightAdapter(private val list: List<weightData>) :
RecyclerView.Adapter<WeightAdapter.MyViewHolder>() {
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val time: TextView = itemView.findViewById(R.id.time)
val weight: TextView = itemView.findViewById(R.id.detail)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.weight_item, parent, false)
return MyViewHolder(view)
}
override fun getItemCount(): Int {
return list.size
}
//模型与视图的绑定
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val w = list[position]
holder.time.text = w.time
holder.weight.text = w.weight.toString()
}
}
}
不具体讲解了,大家直接看代码吧,写的不好,也是刚学的。正常情况直接搬运代码就可以运行出来,能理解就理解一下原理,理解不了就直接照着画吧
标签:val,示例,list,用法,22.0,import,RecyclerView,view 来源: https://blog.csdn.net/weixin_44766261/article/details/118761285