目录
- RecyclerView是什么
- 如何使用
- RecyclerView 涉及到的类
- LayoutManager
- 为Item设置不同的布局样式
- 制作拖动的RecyclerView
一、RecyclerView是什么
RecyclerView是Android支持库中的一个控件,用于在列表或网格形式展示大量数据。它是ListView的升级版,提供了更灵活、可定制化的方式来展示和管理数据。
二、如何使用
RecyclerView的使用步骤:
- 创建RecyclerView控件对象
- 设置适配器 : 一般是使用自定义的适配器 , 设置给 RecyclerView 对象 ;
- 创建适配器的布局文件
- 创建并设置布局管理器 : 可以使用预置的布局管理器 , 也可以自定义布局管理器 ;
(1)创建控件
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/home_rv_product"
android:layout_width="1500dp"
android:layout_height="800dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
(2)创建适配器
class HomeProductAdapter(var productList:ArrayList<HomeProductBean>): RecyclerView.Adapter<HomeProductAdapter.MyViewHolder>() {
inner class MyViewHolder(view: View): RecyclerView.ViewHolder(view){
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.home_item_home_product,parent,false)
return MyViewHolder(view)
}
override fun getItemCount(): Int {
return productList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="200dp"
android:layout_height="270dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:background="@drawable/dingdian_imge_price_bg">
<ImageView
android:id="@+id/iv_sugar"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:src