Android RecyclerView Load More

本文详细介绍了如何在Android应用中使用RecyclerView实现加载更多功能。通过监听RecyclerView的滚动事件,当用户滚动到列表底部时显示加载视图。在数据源末尾添加一个空元素来触发加载视图,并在数据获取完成后更新列表。具体实现包括适配器的创建、ViewHolder的定义以及在MainActivity中注册滚动监听器和加载更多数据的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I think RecyclerView is very common in android development. It is a useful component in android application.It is necessary to know how to implement loading more function with RecyclerView in android application.How is this implemented?

Typically, we load elements to the adapter from a data source.

In order to detect that the user has scrolled to the end of RecyclerView, we need to implement OnScrollListener().

In order to show the loading view at the bottom of RecyclerView.We could add a NULL element to the end of the data source.After adding a NULL element, we notify the adapter using notifyItemInserted() method.So that the loading view will be showing. And Then to fetch the next set of elements.

Once the next set of elements is obtained, we remove the NULL element and add the next set of elements to the bottom of the data source.

Let’s code!
The code for the activity_main.xml is given below:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

The layout for the rows of RecyclerView is defined in item_row.xml,its code is given below:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp">

    <TextView
        android:id="@+id/tvItem"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Item X" />
</androidx.cardview.widget.CardView>

The layout for loading view is given below. it is defined in item_loading.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

To use RecycleView in application, we need to define an adapter. It is given below:

package com.example.pulluprefresh

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter

class RecyclerVewAdapter constructor(var mItemList:MutableList<String?>) : Adapter<RecyclerView.ViewHolder>() {

    class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val mTvItem: TextView = itemView.findViewById(R.id.tvItem)
    }

    class LoadingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = when (viewType) {
        VIEW_TYPE_ITEM -> {
            ItemViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_row, parent, false))
        }
        else -> {
            LoadingViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_loading, parent, false))
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is ItemViewHolder) {
            holder.mTvItem.text = mItemList[position]
        }
    }

    override fun getItemCount(): Int = mItemList.size

    override fun getItemViewType(position: Int): Int = if (mItemList[position] == null) VIEW_TYPE_LOADING else VIEW_TYPE_ITEM

    companion object {
        const val VIEW_TYPE_ITEM: Int = 0
        const val VIEW_TYPE_LOADING: Int = 1
    }
}

Note:getItemViewType() is where we check each element of the data source. If the data is NULL, we set the view type as 1 else 0.
Based on the view type, we instantiate the ViewHolder in onCreateViewHolder(). We could bind the data to the view according to view type in onBindViewHolder().

Here is MainActivity code. We instantiate adapter inside MainActivity.Here we also register OnScrollListener on RecyclerView, where we check if the user has scrolled the the end of the data source. If the bottom-most element is visible, we show the loading view and to fetch the set of data.

package com.example.pulluprefresh

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {
    lateinit var recyclerView: RecyclerView
    private var mItemList: MutableList<String?> = mutableListOf()
    private var isLoading = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        recyclerView = findViewById(R.id.recyclerView)
        mockData()
        initAdapter()
        initScrollListener()
    }

    private fun mockData() {
        for (i in 0 until 10) {
            mItemList.add("Item $i")
        }
    }

    private fun initAdapter() {
        recyclerView.adapter = RecyclerVewAdapter(mItemList)
    }

    private fun initScrollListener() {
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val linearLayoutManager = recyclerView.layoutManager as LinearLayoutManager
                if(!isLoading && linearLayoutManager.findLastCompletelyVisibleItemPosition() == mItemList.size - 1 ){
                    loadMore()
                    isLoading = true
                }
            }
        })
    }
    private fun loadMore(){
        mItemList.add(null)
        recyclerView.adapter?.notifyItemInserted(mItemList.size - 1)
        val handler = Handler()
        handler.postDelayed({
            mItemList.removeAt(mItemList.size - 1)
            recyclerView.adapter?.notifyItemRemoved(mItemList.size)
            for(i in mItemList.size .. mItemList.size+10){
                mItemList.add("Item $i")
            }
            recyclerView.adapter?.notifyDataSetChanged()
            isLoading = false
        },2000)
    }
}

Demo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值