效果图
主要代码
- 主界面:RecyclerViewActivity
class RecyclerViewActivity : AppCompatActivity() {
private lateinit var adapter: RvAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler_view)
initRecyclerView()
loadData()
}
private fun initRecyclerView() {
adapter = RvAdapter()
recyclerView.adapter = adapter
//设置布局类型
recyclerView.layoutManager = LinearLayoutManager(this)
//如果要实现横向列表,就采用下面的布局方式
//recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
//添加安卓自带的分割线
recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
}
private fun loadData() {
val data = ArrayList<String>()
for (i in 0..50) {
data.add("text-$i")
}
adapter.setData(data)
}
}
- 主界面布局文件:activity_recycler_view.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</LinearLayout>
- 列表adapter:RvAdapter
class RvAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var mDataList = mutableListOf<String>()
private lateinit var mContext: Context
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val data = mDataList[position]
holder.itemView.textView.text = data
holder.itemView.setOnClickListener {
setOnItemClickListener(data)
}
}
fun setData(dataList: List<String>) {
mDataList.clear()
mDataList.addAll(dataList)
notifyDataSetChanged()
}
override fun getItemCount(): Int = mDataList.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
mContext = parent.context
val view = LayoutInflater.from(mContext).inflate(R.layout.item_rv, parent, false)
return ViewHolder(view)
}
private fun setOnItemClickListener(data: String) {
Toast.makeText(mContext, data, Toast.LENGTH_SHORT).show()
}
class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!)
}
- adapter布局文件:item_rv.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:gravity="center"
android:textSize="20sp"
android:text="text" />
</LinearLayout>
源代码
https://gitee.com/cxyzy1/androidStart/tree/master/recyclerViewDemo
网友评论