Android 控件RecyclerView的使用
RecyclerView是谷歌V7包下新增的控件,用来替代ListView的使用,RecyclerView灵活可配置,可自定义并可重复利用的item,高度解耦
RecyclerView的基本流程
布局管理器<----->适配器<---->数据
- LayoutManager
- Adapter
- ViewHolder
三种LayoutManager布局管理器 - LinearLayoutManager线性布局管理器
- GridLayoutManager切换为网格布局管理器
- StaggeredGridLayoutManager瀑布流布局管理器
项目介绍:点击添加数据,会在下方出现由线性布局管理器设置的布局,点击切换布局按钮,会切换为切换为网格布局,再次点击切换按钮,会切换为瀑布流布局,再次点击切换布局按钮,切换回线性布局,依次类推;当点击插入一条数据时,会在布局中添加一条数据,点击删除即删除所添加的数据
项目完整录屏:
项目实现:
1.在build.gradle中添加依赖
implementation 'androidx.recyclerview:recyclerview:1.0.0'
2.创建存放每条数据的xml资源文件item_layout.xml
分为两部分,ImageView和TextView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#A4D3EE"
android:layout_margin="4dp">
<ImageView
android:id="@+id/iv"
android:layout_width="88dp"
android:layout_height="88dp"
android:scaleType="fitXY"/>
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="22sp"
android:textColor="#fff"
android:gravity="center_vertical"
android:layout_marginLeft="8dp"/>
</LinearLayout>
3.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加数据"
android:onClick="onAddDataClick"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text