1 基本介绍

参照 kotlin官网:使用 RecyclerView 显示可滚动列表的 案例实现

功能:采用RecyclerView 空间实现图片和文字的滚动浏览

在下图显示的序列中,可以看到一个填充了数据 ABC 的视图。当该视图滚动出屏幕之后,RecyclerView 会重复使用该视图来显示新数据 XYZ

学习内容

  • 如何使用 RecyclerView 显示数据列表?
  • 如何将代码构成软件包?
  • 如何将 Adapter 与 RecyclerView 配合使用以自定义各列表项的外观?

2 创建项目

2.1 创建project

  1. 在 Android Studio 中,使用 Empty Activity 模板启动一个新的 Kotlin 项目。
  2. 输入 affirmations 作为应用的 Name,输入 com.example.affirmations 作为 Package name,然后选择 API Level 21 作为 Minimum SDK
  3. 点击 Finish 创建项目。

2.2 设置数据列表

下面内容添加到项目中。

  • 字符串资源:它们将在应用中显示为 需要显示的语句
  • 数据来源:它将向应用提供需要显示的语句的列表。

打开 app > res > values > strings.xml

将需要显示的语句输入string

<resources><string name="app_name">Affirmations</string><string name="Affirmation1">1I am strong.</string><string name="Affirmation2">2 I believe in myself.</string><string name="Affirmation3">3 Each day is a new opportunity to grow and be a better version of myself.
</string><string name="Affirmation4">4 Every challenge in my life is an opportunity to learn from.</string><string name="Affirmation5">5 I have so much to be grateful for.</string><string name="Affirmation6">6 Good things are always coming into my life.</string><string name="Affirmation7">7 New opportunities await me at every turn.</string><string name="Affirmation8">8 I have the courage to follow my heart.</string><string name="Affirmation9">9 Things will unfold at precisely the right time.</string><string name="Affirmation10">10 I will be present in all the moments that this day brings.</string></resources>

您已添加了字符串资源,可以在代码中将其引用为 R.string.affirmation1 或 R.string.affirmation2

2.3 创建新的软件包(文件夹)

就像您可以将文书整理成文件和文件夹一样,您同样可以将代码组织成文件和软件包。

图中显示了三个大的软件包(文件夹):一个用于您的代码 (com.example.affirmations),另外两个用作测试文件(com.example.affirmations (androidTest) 和 com.example.affirmations (test))。

软件包的名称由几个单词组成,单词间以句点进行分隔。

2.3.1创建软件包

  1. 在 Android Studio 的 Project 窗格中,右键点击 app > java > com.example.affirmations,然后依次选择 New > Package

在弹出式窗口中,将 model 附加到建议的软件包名称末尾,创建了 model文件夹。

类似的, 创建adapter,data 软件包。

2.3.2在model 软件包,创建类

右键点击 com.example.affirmations.model 软件包,然后依次选择 New > Kotlin File/Class

  1. 在弹出式窗口中,选择 Class,然后输入 Affirmation 作为类的名称。系统将在 model 软件包中创建一个名为 Affirmation.kt 的新文件。
  2. 在类定义前添加 data 关键字,使 Affirmation 成为数据类。这样做会出错,因为数据类必须至少定义一个属性。
  3. 分别创建stringResocureId 和 imageResourceId。 用于后面的文本和图片显示
package com.example.affirmations.modelimport androidx.annotation.DrawableRes
import androidx.annotation.StringRes/*
在类定义前添加 data 关键字,使 Affirmation 成为数据类。
在创建 Affirmation 的实例时,您需要传入自我肯定话语字符串的资源 ID。资源 ID 是一个整数。*/data class Affirmation(@StringRes val stringResourceId:Int,@DrawableRes val imageResourceId :Int) {}

2.4创建要作为数据源的类

准备数据是一项需要单独处理的工作,因此请将 Datasource 类放在单独的 data 软件包中。

  1. 在 Android Studio 的 Project 窗口中,右键点击 app > java > com.example.affirmations,然后依次选择 New > Package
  2. 输入 data 作为软件包名称的最后一部分。
  3. 右键点击 data 软件包,然后选择 new Kotlin File/Class
  4. 输入 Datasource 作为类名称。
  5. 在 Datasource 类中,创建一个名为 loadAffirmations() 的函数。

loadAffirmations() 函数需要返回 Affirmations 的列表。为此,您可以创建一个列表,并使用每个资源字符串的 Affirmation 实例填充该列表。

  1. 将 List<Affirmation> 声明为 loadAffirmations() 方法的返回值类型。
  2. 在 loadAffirmations() 的主体中,添加 return 语句。
  3. 在 return 关键字之后,调用 listOf<>() 创建一个 List
  4. 在尖括号 <> 内,将列表项的类型指定为 Affirmation。根据需要导入 com.example.affirmations.model.Affirmation
  5. 在圆括号内创建 Affirmation,传入 R.string.affirmation1 作为资源 ID,如下所示。

由于类Affirmation 包括文本和图片,因此参数为这2个的id。后面将用于文本和图片的显示。

package com.example.affirmations.dataimport com.example.affirmations.R
import com.example.affirmations.model.Affirmationclass Datasource{fun loadAffirmations(): List<Affirmation> {return listOf<Affirmation>(Affirmation(R.string.Affirmation1, R.drawable.image1), // THERE  need comma ,, between itemAffirmation(R.string.Affirmation2,R.drawable.image2),Affirmation(R.string.Affirmation3,R.drawable.image3),Affirmation(R.string.Affirmation4, R.drawable.image4),Affirmation(R.string.Affirmation5, R.drawable.image5),Affirmation(R.string.Affirmation6,R.drawable.image6),Affirmation(R.string.Affirmation7,R.drawable.image7),Affirmation(R.string.Affirmation8,R.drawable.image8),Affirmation(R.string.Affirmation9,R.drawable.image9),Affirmation(R.string.Affirmation10,R.drawable.image10))}
}

2.5 将 RecyclerView 添加到应用

您将设置一个 RecyclerView 来显示 Affirmations 的列表。

(这个有点不好理解:实际就是一个窗口 用recyclerview显示文本和图片,由于图片比较大,因此各列之间会滚动来显示)

将 RecyclerView 添加到布局中

Affirmations 应用由一个名为 MainActivity 的 activity 及其名为 activity_main.xml 的布局文件组成。首先,您需要将 RecyclerView 添加到 MainActivity 的布局中。

  1. 打开 activity_main.xml (app > res > layout > activity_main.xml)。
  2. 切换到 Split 视图(如果您尚未使用该视图)

当前布局使用的是 ConstraintLayout。如果想在布局中放置多个子视图,那么 ConstraintLayout 就是理想而又灵活的选择。不过,因为您的布局只有一个子视图 RecyclerView,所以您可以切换到更简单的名为 FrameLayout 的 ViewGroup,这才是只包含一个子视图时应该使用的选择。

在 XML 文件中,将 ConstraintLayout 替换为 FrameLayout。完成后的布局应如下所示。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<!--change constraintlayout to framelayout-->
<FrameLayout 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.recyclerview.widget.RecyclerViewandroid:id="@+id/recycler_view"android:layout_width="match_parent"android:layout_height="match_parent"android:scrollbars="vertical"app:layoutManager="LinearLayoutManager" /></FrameLayout>

为了能够滚动浏览超出屏幕长度的垂直项目列表,您需要添加一个垂直滚动条。

在 RecyclerView 内,添加设为 vertical 的 android:scrollbars 属性。

2.6 为 RecyclerView 实现 Adapter

RecyclerView 中的每个列表项都有自己的布局,您可以在单独的布局文件中定义这些布局。由于您只需要显示字符串,因此可将 TextView 用于列表项布局。

  1. 在 res > layout 中,新建名为 list_item.xml 的空 File
  2. 在 Code 视图中打开 list_item.xml
  3. 添加 id 为 item_title 的 TextView
  4. 针对 layout_width 和 layout_height 添加 wrap_content,如下面的代码所示。这里使用Matrial属性
<?xml version="1.0" encoding="utf-8"?>
<!--围绕现有的 LinearLayout. 添加 MaterialCardView。  -->
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="8dp"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><ImageViewandroid:layout_width="match_parent"android:layout_height="194dp"android:id="@+id/item_image"android:importantForAccessibility="no"android:scaleType="centerCrop"/><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/item_title"android:textSize="20dp"android:padding="16dp"android:textAppearance="?attr/textAppearanceHeadline6"/></LinearLayout></com.google.android.material.card.MaterialCardView>

您也可以使用 File > New > Layout Resource File,将 File name 设为 list_item.xml,并以 TextView 作为 Root element。然后,更新生成的代码以匹配上面的代码。

新版本的图有区别,记得更改为TextView。

2.7 创建 ItemAdapter 类

  1. 在 Android Studio 的 Project 窗格中,右键点击 app > java > com.example.affirmations,然后依次选择 New > Package
  2. 输入 adapter 作为软件包名称的最后一部分。
  3. 右键点击 adapter 软件包,然后依次选择 New > Kotlin File/Class
  4. 输入 ItemAdapter 作为类名称,完成创建操作,系统将打开 ItemAdapter.kt 文件。

您需要将一个参数添加到 ItemAdapter 的构造函数中,以便将语句列表传入 Adapter。

  1. 将一个参数添加到 ItemAdapter 的构造函数中,该参数是名为 dataset、类型为 List<Affirmation> 的 val。根据需要导入 Affirmation
  2. 由于 dataset 仅在此类中使用,因此请将其设为 private

ItemAdapter.kt

import com.example.affirmations.model.Affirmationclass ItemAdapter(private val dataset: List<Affirmation>) {}
  1. 一个参数添加到 ItemAdapter 的构造函数中,该参数是名为 context、类型为 Context 的 val。请将其作为构造函数中的第一个参数。
class ItemAdapter(private val context: Context, private val dataset: List<Affirmation>) {}

详细内容如下:

package com.example.affirmations.adapterimport android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.affirmations.R
import com.example.affirmations.model.Affirmation
/*** Adapter for the [RecyclerView] in [MainActivity]. Displays [Affirmation] data object.* 这个申明太奇怪,怎么能将class 申明类型为 类里的成员 ItemAdapter.ItemViewHolder*/
class ItemAdapter(private val context: Context,private val dataset: List<Affirmation>):RecyclerView.Adapter<ItemAdapter.ItemViewHolder>( ){// Provide a reference to the views for each data item// Complex data items may need more than one view per item, and// you provide access to all the views for a data item in a view holder.// Each data item is just an Affirmation object.class ItemViewHolder(private  val view: View) : RecyclerView.ViewHolder( view){val textView: TextView= view.findViewById(R.id.item_title) //   textview--item_titleval imageView: ImageView = view.findViewById((R.id.item_image))}/*** Create new views (invoked by the layout manager)* 在 onCreateViewHolder() 方法中,从提供的上下文(parent 的 context)中获取 LayoutInflater 的实例。* 布局膨胀器知道如何将 XML 布局膨胀为视图对象的层次结构。*/override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {// create a new view// 奇怪,将以下参数改为true, 再改为false, 所有affirmation的文本就能显示。之前只能显示一个。/*** public View inflate (XmlPullParser parser,ViewGroup root,boolean attachToRoot)parser  XmlPullParser: XML dom node containing the description of the view hierarchy.root   ViewGroup: Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.) This value may be null.attachToRoot  boolean: Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.*/val adapterLayout= LayoutInflater.from(parent.context).inflate(R.layout.list_item,parent,false)return  ItemViewHolder(adapterLayout)}/*** Replace the contents of a view (invoked by the layout manager)* 调用 context.resources.getString() 并传入字符串资源 ID。返回的字符串可在 holder ItemViewHolder 中设为 textView 的 text*/override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {val item= dataset[position]holder.textView.text = context.resources.getString(item.stringResourceId)holder.imageView.setImageResource(item.imageResourceId)}/*** Return the size of your dataset (invoked by the layout manager)*/override fun getItemCount(): Int {return dataset.size}
}

重构函数的创建:

class ItemAdapter(private val context: Context,private val dataset: List<Affirmation>
) : RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() {class ItemViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {val textView: TextView = view.findViewById(R.id.item_title)}
}

您会看到一条错误消息,因为您需要从 RecyclerView.Adapter 实现一些抽象方法。

  1. 将光标放在 ItemAdapter 上,然后按 Command+I(在 Windows 上,则请按 Control+I)。系统将列出您需要实现的方法:getItemCount()onCreateViewHolder() 和 onBindViewHolder()

使用 Shift+click 将三个函数全部选中,然后点击 OK

以上内容 做起来的难以理解,kotlin的函数封装太多。只能去适应。

2.8 main_activity.kt

您需要使用 Datasource 和 ItemAdapter 类在 RecyclerView 中创建和显示列表项。您可以在 MainActivity 中执行此操作。

  1. 打开 MainActivity.kt
  2. 在 MainActivity, 中,转到 onCreate() 方法。在调用 setContentView(R.layout.activity_main). 之后,插入以下步骤中所述的新代码。
  3. 创建 Datasource 的实例,并对其调用 loadAffirmations() 方法。将返回的语句列表存储在名为 myDataset 的 val 中。
val myDataset = Datasource().loadAffirmations()
  1. 为了指示 recyclerView 使用您创建的 ItemAdapter 类,请创建一个新的 ItemAdapter 实例。ItemAdapter 应该有两个参数:此 activity 的上下文 (this) 和 myDataset 中的自我肯定话语。
  2. 将 ItemAdapter 对象分配给 recyclerView 的 adapter 属性。
recyclerView.adapter = ItemAdapter(this, myDataset)

由于 activity 布局中的 RecyclerView 布局大小是固定的,因此您可以将 RecyclerView 的 setHasFixedSize 参数设为 true

总的代码如下:

package com.example.affirmationsimport androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.affirmations.adapter.ItemAdapter
import com.example.affirmations.data.Datasourceclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)//创建 Datasource 的实例,并对其调用 loadAffirmations() 方法。将返回的自我肯定话语列表存储在名为 myDataset 的 val 中。// Initialize data.val myDataset = Datasource().loadAffirmations()
//创建一个名为 recyclerView 的变量,并使用 findViewById() 查找对布局中 RecyclerView 的引用。val recylceView = findViewById<RecyclerView>(R.id.recycler_view)recylceView.adapter = ItemAdapter(this,myDataset)// Use this setting to improve performance if you know that changes// in content do not change the layout size of the RecyclerView/*** 虽然显示了内容,但还是没有搞清楚内部的逻辑关系*/recylceView.setHasFixedSize(true)//val textView: TextView = findViewById(R.id.textView)//textView.text = Datasource().loadAffirmations().size.toString()}
}

3  设置图标和显示图片

图片地址:下载图片

将图片文件下载到您的计算机上。应该有十张图片,应用中的每句话语各有一张图片。这些文件的名称应该是从 image1.jpg 到 image10.jpg

在 Android Studio 中,将图片从您的计算机复制到项目的 res > drawable 文件夹 (app/src/main/res/drawable) 中。一旦将这些资源添加到应用,您便能够使用资源 ID(如 R.drawable.image1)从代码访问这些图片。(您可能必须重建代码,才能让 Android Studio 找到图片。)

运行app, 结果如下:

可以修改图片显示列

如何实现点击图片放大显示呢?

4  设置app的图标

您将更新应用图标,需要把原来的图标删除。

  1. 下载应用图标文件 ic_launcher_foreground.xml 和 ic_launcher_background.xml。如果您的浏览器显示了相应的文件,请依次选择文件 > 网页另存为…,以将其保存到计算机上,而不必下载文件。
  2. 在 Android Studio 中,删除两个文件,即 drawable/ic_launcher_background.xml 和 drawable-v24/ic_launcher_foreground.xml 文件,因为这些文件用于以前的应用图标。您可以取消选中 Safe delete (with usage search) 框。
  3. 然后右键点击 res > drawable 文件夹,再依次选择 New > Image Asset

4.在 Configure Image Asset 窗口中,确保选择了 Foreground layer

5.在它下面,找到 Path 标签。

6.点击 Path 文本框内的文件夹图标。

7.找到并打开您下载到计算机上的 ic_launcher_foreground.xml 文件。

8.切换到 Background Layer 标签页。

9.点击 Path 文本框内的 Browse 图标。

10.在计算机上查找并打开 ic_launcher_background.xml 文件。不需要进行其他更改。

11.点击 Next

模拟器安装的图标已经变化。

5 辅助文件

color

<?xml version="1.0" encoding="utf-8"?>
<resources><color name="purple_200">#FFBB86FC</color><color name="purple_500">#FF6200EE</color><color name="purple_700">#FF3700B3</color><color name="teal_200">#FF03DAC5</color><color name="teal_700">#FF018786</color><color name="black">#FF000000</color><color name="white">#FFFFFFFF</color><!--  add  color type --><color name="blue_200">#FF90CAF9</color><color name="blue_500">#FF2196F3</color><color name="blue_700">#FF1976D2</color><color name="green">#1B5E20</color><color name="green_dark">#003300</color><color name="green_light">#A5D6A7</color><color name="blue">#0288D1</color><color name="blue_dark">#005B9F</color><color name="blue_light">#81D4FA</color>
</resources>

theme.xml

<resources xmlns:tools="http://schemas.android.com/tools"><!-- Base application theme. --><style name="Theme.Affirmations" parent="Theme.MaterialComponents.DayNight.DarkActionBar"><!-- Primary brand color. --><item name="colorPrimary">@color/green</item><item name="colorPrimaryVariant">@color/green_dark</item><item name="colorOnPrimary">@color/white</item><!-- Secondary brand color. --><item name="colorSecondary">@color/blue</item><item name="colorSecondaryVariant">@color/blue_dark</item><item name="colorOnSecondary">@color/black</item><!-- Status bar color. --><item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item><item name="textInputStyle">@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox</item><item name="radioButtonStyle">@style/Widget.AppCompat.CompoundButton.RadioButton</item><item name="switchStyle">@style/Widget.AppCompat.CompoundButton.Switch</item><!-- Customize your theme here. --></style>
</resources>

相关代码已传到资源里了, 点我下载

Android Studio kotlin编程实现图片滑动浏览 stepbystep相关推荐

  1. 第37篇 Android Studio实现点击图片显示信息(四)布局及资源文件

    第37篇 Android Studio实现点击图片显示信息(四)布局及资源文件 4.布局文件 4.1.strings.xml 4.布局文件 整体是一个垂直布局,然后在设置一些水平布局就行了. < ...

  2. Android studio 实现打电话发短信浏览网页功能 android开发小实验

    Android studio 实现打电话发短信浏览网页功能 android开发小实验 目标: android studio 实现打电话 发短信 浏览网站的功能 先在布局里面定义几个按钮 分别为 打电话 ...

  3. 借助Android Studio生成图标(图片)drawable文件夹下的xml文件

    目录 一.准备图标或者图片 二.AS新建Vector Asset 如标题所示,借助Android Studio生成图标(图片)的xml文件,存放在drawable文件夹下. 一.准备图标或者图片 本人 ...

  4. Android Studio - Kotlin 改变控件字体

    Android Studio - Kotlin 改变控件字体 如改变 textView 的字体( FontFamily ) val typeface = Typeface.createFromAsse ...

  5. Android Studio调用python读取图片(使用服务器paddlehub处理图片)

    Android Studio调用python读取图片 一.主要任务 二.环境配置 1.创建一个android studio项目 2.配置项目gradle 3.配置app下的gradle 三.demo测 ...

  6. 第34篇 Android Studio实现点击图片显示信息(一)需求

    第34篇 Android Studio实现点击图片显示信息(一)需求 1.需求 1.1.效果 1.2.功能 1.3.RadioButton实现 1.4.设置RadioButton样式 1.需求 1.1 ...

  7. Android Studio||动态改变xml图片位置+背景/旋转+平移/AnimationSet/java读取drawable图

    step by step. 目录 参考: 平移(TranslatAnimation) 旋转(RotateAnimation) AnimationSet xml:(正常设置即可) java: java读 ...

  8. 在android studio中制作九宫格图片

    本文介绍如何在android studio中制作一张九宫格图片. 1.选中准备进行处理的图片*.png,直接修改名为*.9.png.放入android studio 工程的drawable目录下.(. ...

  9. Android Studio制作.9.png图片

    .9图是andriod平台的应用软件开发里的一种特殊的图片形式,文件扩展名为:.9.png,.9图可以将图片横向和纵向同时进行拉伸,以实现在多分辨率下的完美显示效果..9图最常用的是聊天记录的背景框, ...

最新文章

  1. cmd命令简单别木马的蛛丝马迹
  2. MySQL启动报:[ERROR] The server quit without updating
  3. easyui treegrid php,easyUI TreeGrid
  4. mysql ES 同步中间件
  5. 安装部署及升级到Exchange Server 2010
  6. SpringBoot2 集成日志,复杂业务下的自定义实现
  7. linux scp限制传输速度
  8. 使用爬虫爬去网上的图片并保存
  9. android wifi信号强度命令,Android显示wifi信号强度以及周边信号的代码
  10. MATLAB中的均值与方差求法(mean,var,std函数使用)
  11. proteus常用器件
  12. Smart原则和PDCA循环
  13. 南通大学《构建之法》课程助教总结
  14. python有道翻译
  15. python 开机自动切换必应壁纸
  16. Python-字符串
  17. 在CSDN中如何快速简单方便的免费下载资料
  18. 可行解、最优解、基解、基可行解、基最优解
  19. 扫地机器人漫谈(三):扫地机的传感器
  20. 数据分析应有的逻辑思维及分析方法

热门文章

  1. wps的ppt怎么存html,如何将网页快速转换为WPS与WORD文档 ppt怎么转换成word文档
  2. 张朝阳对话俞敏洪:谈宇宙、谈焦虑、谈创业、谈退休、谈人生
  3. 商品销售订单综合分析
  4. android高仿微信表情输入与键盘输入详解
  5. 谜底是计算机的谜语英语,有关英语谜语大全及答案
  6. 著名的斐波那契额数列,1 1 2 3 5 8输出第n项
  7. 上市公司产权和股权性质-区分非国企、国企和央企(2003-2020)
  8. 剑指Offer:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法
  9. 备战腾讯面试经历分享,小伙终获Android岗Offer
  10. linux文件句柄上线的修改,修改Linux文件句柄限制