Android 使用RecycleView实现图片的水平滑动

Android 使用RecycleView实现图片的水平滑动

第一步:首先在布局中添加一个RecycleView控件,在添加之前需要找到build.gradle文件进行第三方插件的下载,代码如下:

    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.android.support:appcompat-v7:28.0.0'

布局代码如下:

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/r1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
        
</LinearLayout>

界面截图:
在这里插入图片描述

第二步:找到控件并绑定ID
在这里插入图片描述
第三步:完成列表的相关操作
首先创建一个xml文件,实现列表的布局,这里只添加ImageView控件来实现图片的显示,代码如下:

<?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="match_parent">
    <ImageView
        android:id="@+id/i1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"/>

</LinearLayout>

界面截图:
在这里插入图片描述
第二:定义一个Adapter1的类来实现列表的功能
在这里插入图片描述

public class Adapter1 {
    
    
}

在该类中继承RecyclerView.Adapter

public class Adapter1 extends RecyclerView.Adapter {
    
    
}

之后把鼠标移至Adapter1,在键盘按Alt+Enter 选择第一个,最后选择ok
在这里插入图片描述
在这里插入图片描述
在倒数第二个花括号中定义一个类

public class ViewHolder extends RecyclerView.ViewHolder
    {
    
    
    }

在该类中填写控件的id
在这里插入图片描述
定义一个数组存放数据

private int[]a;

在这里插入图片描述
更改当前的值
在这里插入图片描述
找到Adapter1.ViewHolder onCreateViewHolder的函数,绑定xml并返回当前的值
在这里插入图片描述
找到onBindViewHolder函数,将获取到的JSON数据传递到指定的控件
在这里插入图片描述
返回数据的长度
在这里插入图片描述
第四步:返回MainActivity.java文件,选择列表显示的样式并显示数据。
在这里插入图片描述
下面是本项目的源代码:
https://download.csdn.net/download/Scxioi0/12920308

猜你喜欢

转载自blog.csdn.net/Scxioi0/article/details/109038002
今日推荐