recycleview设计
要求:在原有作业上选择一个tab添加recycleview显示。
链接: 源码链接.
结果显示:
目录结构
在Fragment中添加RecyclerView
1.在tab01中添加相应控件并布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/t1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/id_content1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:textSize="25sp" />
</LinearLayout>
设置布局为RecyclerView
2.新建一个item.xml布局设置为LinearLayout,效果如下:
3.新建一个自定义的数据类GoodsEntity,在其中定义数据类型以及getter and setter 方法
4.为了数据能够与视图相匹配,必须要创建Adapter适配器
使用适配器需要继承Adapter抽象类,继承该类的时候,必须重写三个方法,这三个方法的作用:
①onCreateViewHolder:创建ViewHolder,该方法会在RecyclerView需要展示一个item的时候回调。重写该方法时,应该使ViewHolder加载item view的布局。这个能发避免了不必要的findViewById操作,提高了性能。
②onBindeViewHolder:该方法在RecyclerView在特定位置展示数据时候回调,把数据绑定、填充到相应的item view中。
③getItemCount:返回数据的数量。
5.最后在weixinFragment中定义和使用recycerview即可运行
在这里统一设置视图的内容,如有需要可以在GoodsEntity类中重构构造函数。