RecyclerView 可以轻松高效地显示大量数据。
RecyclerView回收这些单独的元素。当一个项目滚出屏幕时, RecyclerView 不会破坏它的视图。
RecyclerView 的步骤
build.gradle(app)
dependencies {
implementation "androidx.recyclerview:recyclerview:1.2.1"
}
adapter and view holder
class Day19Adapter(private val dataSet: List<String>) :
RecyclerView.Adapter<Day19Adapter.ViewHolder>() {
/**
* Provide a reference to the type of views that you are using
* (custom ViewHolder).
*/
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val dataView: TextView
init {
dataView = view.findViewById(R.id.textView4)
}
}
// Create new views (invoked by the layout manager)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
// Create a new view, which defines the UI of the list item
val v = LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
return ViewHolder(v)
}
// Replace the contents of a view (invoked by the layout manager)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// Get element from your dataset at this position and replace the
// contents of the view with that element
holder.dataView.text = dataSet[position]
holder.itemView.setOnClickListener {
Toast.makeText(it.context, "第 $position 项被按下", Toast.LENGTH_SHORT).show() }
}
// Return the size of your dataset (invoked by the layout manager)
override fun getItemCount(): Int {
return dataSet.size
}
}
item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="50dp">
<ImageView
android:id="@+id/imgV"
android:layout_width="40dp"
android:layout_height="40dp"
app:srcCompat="@drawable/logo"
android:layout_margin="5dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_gravity="center"/>
<TextView
android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_marginStart="16dp"
android:layout_toEndOf="@+id/imgV"
android:text="GDG Taipei"
android:gravity="center_vertical"
android:textSize="24sp"/>
</RelativeLayout>
Activity:
val listData = ArrayList<String>()
for (i in 0..19) {
listData.add(i.toString())
}
val layoutManager = LinearLayoutManager(this)
layoutManager.orientation = LinearLayoutManager.VERTICAL
val dataList = findViewById<RecyclerView>(R.id.recyclerView)
dataList.layoutManager = layoutManager
dataList.adapter = Day19Adapter(listData)
执行结果:
https://developer.android.com/guide/topics/ui/layout/recyclerview
<<: 让按钮来个酷动态! 操纵DOM事件:CSS 篇 (二)
结语 完成了连续一个月的铁人赛了!当初觉得每天发一篇应该不会太难,甚至还在开赛前屯了四篇,结果事...
程序语言百百种,C++的优势在哪? C++是一种使用广泛的电脑程序设计语言,继承C语言数据类型丰富、...
来轻松聊聊 今天将接续前篇的内容,分享许多排版时常用的效果。 不透明度 opacity属性可以决定元...
前言 今天的题目一样是easy,不过我觉得很值得练习!题目在这边:206. Reverse Link...
前言 嗨嗨!笔者在这跟大家晚安,不知各位今天过得如何啊!有没有利用客制化的读书规划工具,来不断的提升...