欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android学习笔记-RecyclerView的使用(Kotlin)

程序员文章站 2022-06-14 12:19:14
...

RecyclerView

RecyclerView是Android一个更强大的控件,其不仅可以实现和ListView同样的效果,还有优化了ListView中的各种不足。其可以实现数据纵向滚动,也可以实现横向滚动(ListView做不到横向滚动)。

因为RecyclerView属于新增的控件,Android将RecyclerView定义在support库里。若要使用RecyclerView,第一步是要在build.gradle中添加对应的依赖库。

1、添加依赖库
build.gradle

dependencies {
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
}

2、定义实体类
OnePiece.kt

package com.easycol.recyclerviewdemo

class OnePiece (val name: String, val imageId: Int)

3、定义Item的布局
fruit_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_margin="5dp">

    <ImageView
        android:id="@+id/fruitImage"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"/>

    <LinearLayout
        android:orientation="vertical"
        android:layout_marginLeft="10dp"
        android:layout_width="match_parent"
        android:layout_height="50dp">
        <TextView
            android:id="@+id/fruitName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAllCaps="false"
            android:layout_gravity="top"
            android:textSize="17dp"
            />
        <TextView
            android:layout_marginTop="2dp"
            android:text="这是一个副本标题"
            android:textSize="15dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</LinearLayout>

4、定义适配器
OnePieceAdapter.kt

package com.easycol.recyclerviewdemo
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

class OnePieceAdapter(val onePieceList: List<OnePiece>): RecyclerView.Adapter<OnePieceAdapter.ViewHolder>() {
    //自定义item点击的接口
    interface OnItemClickListener {
        fun onClick(position: Int)
    }

    private var itemClickListener: OnItemClickListener? = null

    //提供set方法
    fun setItemClickListener(itemClickListener: OnItemClickListener) {
        this.itemClickListener = itemClickListener
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val fruitImage: ImageView = view.findViewById(R.id.fruitImage)
        val fruitName: TextView = view.findViewById(R.id.fruitName)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.fruit_item, parent, false)
        val  viewHolder = ViewHolder(view)
        return viewHolder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val fruit = onePieceList[position]
        holder.fruitImage.setImageResource(fruit.imageId)
        holder.fruitName.text = fruit.name

        //添加点击事件
        holder.itemView.setOnClickListener{
            itemClickListener!!.onClick(position)
        }
    }

    override fun getItemCount(): Int {
        return onePieceList.size
    }
}

5、自定义分割线,在res->drawable目录下新建布局类
recycle_divider.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid
        android:color="@color/colorAccent"/>
    <size android:height="1dp"/>

</shape>

6、Activity的布局
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</FrameLayout>

7、在Activity中使用
MainActivity.kt

package com.easycol.recyclerviewdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private val fruitList = ArrayList<OnePiece>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //准备数据
        initFruits()

        //瀑布布局
//        val layoutManager = StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
//        recyclerView.layoutManager = layoutManager

        //线性布局
        val linearLayoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = linearLayoutManager

        //添加自定义分割线
        var divider = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
        ContextCompat.getDrawable(this, R.drawable.recycle_divider)?.let { divider.setDrawable(it) }
        recyclerView.addItemDecoration(divider)

      //设置适配器
        val adapter = OnePieceAdapter(fruitList)
        recyclerView.adapter = adapter

        //item点击回调
        adapter!!.setItemClickListener(object: OnePieceAdapter.OnItemClickListener {
            override fun onClick(position: Int) {
                Toast.makeText(applicationContext, "你点击了"+fruitList!![position].name, Toast.LENGTH_SHORT).show()
            }
        })


    }

    private fun initFruits() {
        repeat(2) {
            fruitList.add(OnePiece("路飞", R.drawable.lufei))
            fruitList.add(OnePiece("娜美", R.drawable.namei))
            fruitList.add(OnePiece("乔巴", R.drawable.qiaoba))
            fruitList.add(OnePiece("骷颅", R.drawable.kulu))
            fruitList.add(OnePiece("啦啦", R.drawable.lala))
            fruitList.add(OnePiece("卢克索", R.drawable.lkes))
            fruitList.add(OnePiece("girl", R.drawable.test))
        }
    }
}

效果:
Android学习笔记-RecyclerView的使用(Kotlin)

图片收集来自网络