RecyclerView概述
RecyclerView是Android中非常受欢迎的控件,RecyclerView是官方在Android5.0之后新添加的控件,推出用来替代传统的ListView和GridView列表控件,所以如果你还在使用ListView的话可以替换为RecyclerView了。
对于RecyclerView的使用根据实际项目进行说明,一些功能可能是你现在正在做的,对你有帮助也说不定。
一、RecyclerView基础使用
第一步:在build.gradle
中添加依赖
implementation ("androidx.recyclerview:recyclerview:1.1.0")//可横向滚动
第二步:添加RecyclerView
点开一个布局文件,找到RecyclerView
控件,拖动到要添加的位置即可添加RecyclerView
。
xml代码如下:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="1dp"
android:background="#6750A4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="实例"
android:textColor="#FFFFFF"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="409dp"
android:layout_height="688dp"
android:layout_marginTop="1dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/constraintLayout">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycleview"
android:layout_width="409dp"
android:layout_height="688dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
第三步:再添加一个news_item_layout.xml
的布局文件,用于显示一条数据
在根布局上面设置好每条显示的数据的长宽,并添加内容到根布局里面。
代码如下:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="90dp">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="title"
android:textColor="#000000"
android:textSize="18sp"
app:layout_constraintStart_toSt