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
    }
}
相关推荐
青春男大1 小时前
java栈--数据结构
java·开发语言·数据结构·学习·eclipse
mashagua2 小时前
RPA系列-uipath 学习笔记3
笔记·学习·rpa
沐泽Mu2 小时前
嵌入式学习-QT-Day05
开发语言·c++·qt·学习
锦亦之22332 小时前
cesium入门学习二
学习·html
zhangphil3 小时前
Android绘图Path基于LinearGradient线性动画渐变,Kotlin(2)
android·kotlin
m0_748256143 小时前
前端 MYTED单篇TED词汇学习功能优化
前端·学习
watl03 小时前
【Android】unzip aar删除冲突classes再zip
android·linux·运维
IT古董3 小时前
【机器学习】机器学习的基本分类-半监督学习(Semi-supervised Learning)
学习·机器学习·分类·半监督学习
键盘上的蚂蚁-3 小时前
PHP爬虫类的并发与多线程处理技巧
android
jbjhzstsl4 小时前
lv_ffmpeg学习及播放rtsp
学习·ffmpeg