效果图
RecyclerView
是谷歌推出的融合了ListView
和GridView
且功能更加强大组件,可以在有限的屏幕上显示更多内容,支持三种不同布局:线性LinearLayoutManager
、网格GridLayoutManager
、瀑布流StaggeredGridLayoutManager
。此外,RecyclerView
的复用机制是它的核心部分。线性布局的示例如下:
关键代码
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
val layoutManager: RecyclerView.LayoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = layoutManager
val dataSet = arrayOf("one", "two", "three", "four", "five")
val recyclerViewAdapter: RecyclerView.Adapter<*> = RecyclerViewAdapter(dataSet)
recyclerView.adapter = recyclerViewAdapter
// 设置分割线
val dividerItemDecoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
recyclerView.addItemDecoration(dividerItemDecoration)
}
}
RecyclerView
的适配器代码:
class RecyclerViewAdapter(private val data: Array<String>) : RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.setData(data[position], position)
}
override fun getItemCount(): Int {
return data.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private var textView: TextView? = null
private var pos = -1
//用于显示数据
fun setData(data: String?, position: Int) {
textView!!.text = data
this.pos = position
}
init {
textView = itemView.findViewById(R.id.tv)
itemView.setOnClickListener { Toast.makeText(itemView.context, data[pos] + " is clicked!", Toast.LENGTH_SHORT).show() }
}
}
}
布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</RelativeLayout>
源码地址
https://github.com/yurensan/MaterialDesignDemo
我是予人三,希望大家点赞支持我哦~ 有大家的鼓励我会分享更多内容