Android --- Kotlin学习之路:ViewBinding+Adapter+RecycleView实现垂直列表

FirstFragment.kt

kotlin 复制代码
package com.example.kotlindemo

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlindemo.databinding.FragmentFirstBinding
import com.example.kotlindemo.databinding.ItemViewLinearVerticalBinding

/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class FirstFragment : Fragment(R.layout.fragment_first) {

    private var _binding: FragmentFirstBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentFirstBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.buttonFirst.setOnClickListener {
            findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
        }

        // List的构建
        binding.recycleList.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        binding.recycleList.adapter = MyAdapter()
    }

    inner class MyAdapter: RecyclerView.Adapter<MyViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
           val itemBinding = ItemViewLinearVerticalBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            return MyViewHolder(itemBinding)
        }

        override fun getItemCount(): Int {
            return 20
        }

        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            holder.bind(position)
        }

    }
    class MyViewHolder(val binding: ItemViewLinearVerticalBinding): RecyclerView.ViewHolder(binding.root) {
        fun bind(position: Int) {
            // Here you can bind data to individual items
            binding.itemTitle.text = "Item-- $position"
            // You can add more bindings if your item layout has more views
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

fragment_first.xml

kotlin 复制代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".FirstFragment">
    <com.google.android.material.button.MaterialButton
        android:id="@+id/button_first"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/next"
        tools:ignore="MissingConstraints" />


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycleList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/button_first">

    </androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>

item_view_linear_vertical.xml

kotlin 复制代码
<?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="80dp"
    android:padding="10dp"
    android:orientation="vertical"
    >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="horizontal"
        android:layout_weight="1">

        <ImageView
            android:id="@+id/item_image"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center_vertical"
            android:src="@drawable/icon_jetpack"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:gravity="center_vertical"
            android:orientation="vertical"
            >

            <TextView
                android:id="@+id/item_title"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:text="移动端架构师体系课"
                android:textSize="16sp"
                android:textStyle="bold"
             />

            <TextView
                android:id="@+id/item_message"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:text="移动端架构师体系课"
                android:textSize="14sp"
                android:maxLines="1"
                android:ellipsize="end"
                android:textStyle="bold"
                />

        </LinearLayout>

    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#f3f3f3"/>

</LinearLayout>

如果你想回顾一下传统findViewById传统的Adapter,请参考如下:
FirstFragment.kt

kotlin 复制代码
package com.example.kotlindemo

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlindemo.databinding.FragmentFirstBinding

/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class FirstFragment : Fragment(R.layout.fragment_first) {

    private var _binding: FragmentFirstBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentFirstBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.buttonFirst.setOnClickListener {
            findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
        }

        // List的构建
        binding.recycleList.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        binding.recycleList.adapter = MyAdapter()
    }

    inner class MyAdapter: RecyclerView.Adapter<MyViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            val inflate = LayoutInflater.from(context)
                .inflate(R.layout.item_view_linear_vertical, parent, false)
            return MyViewHolder(inflate)
        }

        override fun getItemCount(): Int {
            return 20
        }

        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            holder.bind(position)
        }

    }
    class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
        private val itemTitle: TextView = itemView.findViewById(R.id.item_title)
        fun bind(position: Int) {
            itemTitle.text = "Item$position"
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
相关推荐
凉、介17 分钟前
Armv8-A virtualization 笔记 (一)
c语言·笔记·学习·嵌入式·虚拟化·hypervisor
楼田莉子25 分钟前
仿Muduo的高并发服务器:LoopThread模块及其ThreadPool模块
linux·服务器·c++·后端·学习
荣月灵的小梅花32 分钟前
Android 给广播接收器增加权限(permission)或signature签名权限
android
装杯让你飞起来啊1 小时前
第 4 周 Unit 2:Jetpack Compose 状态、按钮、计数器与小费计算器
windows·microsoft·kotlin·安卓
菜鸟的日志1 小时前
【嵌入系统】嵌入式学习笔记(一)
windows·笔记·嵌入式硬件·学习·ubuntu·操作系统
沐言人生1 小时前
ReactNative 源码分析4——ReactActivity之加载JSBundle
android·react native
暗夜猎手-大魔王1 小时前
OpenCode提示词工程学习
学习
Slow菜鸟2 小时前
Docker 学习篇(七)| 实战 — 用 Docker 构建 SpringBoot + Vue 全栈项目
spring boot·学习·docker
南境十里·墨染春水2 小时前
linux 学习进展 网络编程 ——TCP 协议 TIME_WAIT 状态详解
linux·网络·学习
薛定e的猫咪2 小时前
(AAMAS 2023)基于广义策略改进优先级的高效多目标学习 GPI - LS/PD
人工智能·学习·机器学习