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
    }
}
相关推荐
Nu11PointerException38 分钟前
JAVA笔记 | ResponseBodyEmitter等异步流式接口快速学习
笔记·学习
数据猎手小k3 小时前
AndroidLab:一个系统化的Android代理框架,包含操作环境和可复现的基准测试,支持大型语言模型和多模态模型。
android·人工智能·机器学习·语言模型
你的小103 小时前
JavaWeb项目-----博客系统
android
风和先行4 小时前
adb 命令查看设备存储占用情况
android·adb
@小博的博客4 小时前
C++初阶学习第十弹——深入讲解vector的迭代器失效
数据结构·c++·学习
AaVictory.5 小时前
Android 开发 Java中 list实现 按照时间格式 yyyy-MM-dd HH:mm 顺序
android·java·list
南宫生5 小时前
贪心算法习题其四【力扣】【算法学习day.21】
学习·算法·leetcode·链表·贪心算法
懒惰才能让科技进步5 小时前
从零学习大模型(十二)-----基于梯度的重要性剪枝(Gradient-based Pruning)
人工智能·深度学习·学习·算法·chatgpt·transformer·剪枝
love_and_hope6 小时前
Pytorch学习--神经网络--搭建小实战(手撕CIFAR 10 model structure)和 Sequential 的使用
人工智能·pytorch·python·深度学习·学习
似霰6 小时前
安卓智能指针sp、wp、RefBase浅析
android·c++·binder