当前位置: 首页 > news >正文

结合viewBinding实现RecyclerView组件的滚动列表显示

RecyclerView是一个列表显示的工具,可以将内容以列表的方式进行显示。在本文中将结合viewBinding来实现数据的绑定。
一、定义实体类
data class Robot(val imageId:Int,val title:String,val message:String)

二、定义单项数据的布局
单项数据的布局item_robot.xml嵌入在CardView中,代码如下所示:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tool"

    android:id="@+id/cardView"
    android:layout_margin="5dp"
    app:cardBackgroundColor="@android:color/holo_blue_bright"
    app:cardCornerRadius="5dp"
    app:cardElevation="3dp"
    app:contentPadding="4dp"

    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@android:mipmap/sym_def_app_icon" />
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <TextView
                android:id="@+id/nameTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Robot"
                android:textSize="20sp" />
            <TextView
                android:id="@+id/descTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="安卓机器人"
                android:textSize="24sp" />
        </LinearLayout>

    </LinearLayout>

</androidx.cardview.widget.CardView>

三、定义适配器
适配器实现将数据和视图的绑定。

class RobotAdapter(val robots:List<Robot>):
    RecyclerView.Adapter<RobotAdapter.ViewHolder>() {
        inner class ViewHolder(val binding: ItemRobotBinding):
            RecyclerView.ViewHolder(binding.root){
            fun bindData(robot:Robot){
                binding.imageView.setImageResource(robot.imageId)
                binding.nameTxt.text = robot.title
                binding.descTxt.text = robot.message
                binding.imageView.setOnClickListener {
                    Snackbar.make(binding.root,"显示${robot.toString()}",Snackbar.LENGTH_LONG).show()
                }
             
            }
        }
    /**创建视图*/
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemRobotBinding.inflate(LayoutInflater.from(parent.context),
            parent,
            false)//视图绑定item_robot.xml
        return ViewHolder(binding)
    }

    /**绑定数据*/
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val robot = robots[position]
        holder.bindData(robot)
    
    }

    override fun getItemCount(): Int=robots.size
}

四、在碎片FirstFragment中加载RecyclerView
修改上一篇"Fragment碎片切换"的FirstFragment的内容
(1)FirstFragment对应的布局fragment_first.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
    android:background="@android:color/holo_green_light"
    android:id="@+id/recyclerView"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AboutFragment"/>

(2)FirstFragment显示滚动列表的处理

object FirstFragment : Fragment() {
    lateinit var binding:FragmentAboutBinding
    lateinit var robots:ArrayList<Robot>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        robots = ArrayList<Robot>()
   
        for(i in 0..10){
            robots.add(Robot(R.mipmap.ic_launcher,"机器人","编号:${i+1}"))
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentAboutBinding.inflate(inflater,container,false)
        val adapter = RobotAdapter(robots)
        binding.recyclerView.layoutManager =
            StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL)//瀑布布局显示
        binding.recyclerView.adapter = adapter

        return binding.root
    }
}

运行结果如下
滚动列表显示的效果

参考文献
《Android移动应用开发(微课版)》 陈轶 清华大学出版社 
 ISBN:978-7-302-59734-6

相关文章:

  • 【C++】STL——stack和queue(万字详解)
  • Kunyu安装使用教程(linux)
  • 34岁本科男,做了5年功能测试想转行,除了进厂还能干什么?
  • 数据库--mysql(SQL语句)
  • 论文分享 | SpeechFormer: 利用语音信号的层次化特性提升Transformer在认知性语音信号处理领域中的性能
  • JavaEE之CSSⅠ(前端)
  • [ 英语 ] 马斯克抱水槽“入主”推特总部中那句 Let that sink in 到底是什么梗?
  • 中国海底电缆行业发展前景及投资风险预测分析报告
  • 计算机网络【UDP与TCP协议(三次握手、四次挥手)】
  • 爱奇艺开源的高性能网络安全监控引擎
  • JAVA房产交易系统计算机毕业设计Mybatis+系统+数据库+调试部署
  • 【MySQL数据库和JDBC编程】第三章-第二节:MySQL的增删查改进阶篇
  • [深度学习] 名词解释--正则化
  • 2022第二届中国高校大数据竞赛A题(实时更新)
  • Yocto系列讲解[实战篇]88 - 离线没网络的情况下构建和编译
  • 2017届校招提前批面试回顾
  • axios 和 cookie 的那些事
  • DOM的那些事
  • ECMAScript入门(七)--Module语法
  • Facebook AccountKit 接入的坑点
  • Git初体验
  • idea + plantuml 画流程图
  • php面试题 汇集2
  • rabbitmq延迟消息示例
  • Rancher如何对接Ceph-RBD块存储
  • SOFAMosn配置模型
  • vue和cordova项目整合打包,并实现vue调用android的相机的demo
  • 关于 Linux 进程的 UID、EUID、GID 和 EGID
  • 那些年我们用过的显示性能指标
  • 入门级的git使用指北
  • 探索 JS 中的模块化
  • 延迟脚本的方式
  • 一个项目push到多个远程Git仓库
  • NLPIR智能语义技术让大数据挖掘更简单
  • ​ssh免密码登录设置及问题总结
  • # .NET Framework中使用命名管道进行进程间通信
  • (iPhone/iPad开发)在UIWebView中自定义菜单栏
  • (Redis使用系列) Springboot 使用redis实现接口Api限流 十
  • (多级缓存)缓存同步
  • (附表设计)不是我吹!超级全面的权限系统设计方案面世了
  • (附程序)AD采集中的10种经典软件滤波程序优缺点分析
  • (转)c++ std::pair 与 std::make
  • (转)我也是一只IT小小鸟
  • .Net Core 中间件验签
  • .NET/C# 利用 Walterlv.WeakEvents 高性能地定义和使用弱事件
  • .net访问oracle数据库性能问题
  • .NET框架设计—常被忽视的C#设计技巧
  • .NET正则基础之——正则委托
  • .php文件都打不开,打不开php文件怎么办
  • .考试倒计时43天!来提分啦!
  • /bin、/sbin、/usr/bin、/usr/sbin
  • [2019/05/17]解决springboot测试List接口时JSON传参异常
  • [AIGC] Spring Interceptor 拦截器详解
  • [BZOJ3223]文艺平衡树
  • [Bzoj4722]由乃(线段树好题)(倍增处理模数小快速幂)