如何在 Android 中使用 Kotlin 实现 RecyclerView 的无限列表?
此示例演示了如何在 Android 中使用 Kotlin 实现 RecyclerView 的无限列表。
步骤 1 − 在 Android Studio 中创建一个新项目,转到文件 ⇒ 新建项目,并填写所有必需的详细信息以创建新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" app:cardElevation="2dp" app:cardUseCompatPadding="true"> <TextView android:id="@+id/textViewItem" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:textColor="@android:color/holo_blue_bright" android:textStyle="bold" /> </androidx.cardview.widget.CardView>
步骤 3 − 将以下代码添加到 src/MainActivity.kt
import android.os.Bundle import android.os.Handler import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { lateinit var recyclerView: RecyclerView lateinit var recyclerViewAdapter: RecyclerViewAdapter var rowsArrayList: ArrayList<String> = ArrayList() var isLoading = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" recyclerView = findViewById(R.id.recyclerView) populateData() initAdapter() initScrollListener() } 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) { if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == rowsArrayList.size − 1) { //bottom of list! loadMore() isLoading = true } } } }) } private fun initAdapter() { recyclerViewAdapter = RecyclerViewAdapter(rowsArrayList) recyclerView.layoutManager = LinearLayoutManager(applicationContext) recyclerView.adapter = recyclerViewAdapter } private fun populateData() { for (i in 0..9) { rowsArrayList.add("Number $i") } } private fun loadMore() { rowsArrayList.add(null.toString()) recyclerViewAdapter.notifyItemInserted(rowsArrayList.size − 1) val handler = Handler() handler.postDelayed(Runnable { rowsArrayList.removeAt(rowsArrayList.size − 1) val scrollPosition = rowsArrayList.size recyclerViewAdapter.notifyItemRemoved(scrollPosition) var currentSize = scrollPosition val nextLimit = currentSize + 10 while (currentSize − 1 < nextLimit) { rowsArrayList.add("Number $currentSize") currentSize++ } recyclerViewAdapter.notifyDataSetChanged() isLoading = false }, 2000) } }
步骤 4 − 创建一个新的类 RecyclerViewAdapter.kt 并添加以下代码 −
import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import android.widget.TextView import androidx.annotation.NonNull import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder class RecyclerViewAdapter internal constructor(private val itemList: List<String>) : RecyclerView.Adapter<ViewHolder>() { private val viewItemType = 0 @NonNull override fun onCreateViewHolder( @NonNull parent: ViewGroup, viewType: Int ): ViewHolder { return if (viewType == viewItemType) { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_row, parent, false) ItemViewHolder(view) } else { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_loading, parent, false) LoadingViewHolder(view) } } override fun onBindViewHolder(@NonNull viewHolder: ViewHolder, position: Int) { if (viewHolder is ItemViewHolder) { populateItemRows(viewHolder, position) } else if (viewHolder is LoadingViewHolder) { showLoadingView(viewHolder, position) } } override fun getItemViewType(position: Int): Int { return viewItemType } private inner class ItemViewHolder internal constructor(@NonNull itemView: View) : ViewHolder(itemView) { internal var tvItem: TextView = itemView.findViewById(R.id.textViewItem) } private class LoadingViewHolder internal constructor(itemView: View) : ViewHolder(itemView) { var progressBar: ProgressBar = itemView.findViewById(R.id.progressBar) } override fun getItemCount(): Int { return itemList.size } private fun showLoadingView(viewHolder: LoadingViewHolder, position: Int) {} private fun populateItemRows(viewHolder: ItemViewHolder, position: Int) { val item = itemList[position] viewHolder.tvItem.text = item } }
步骤 5 − 创建一个布局资源文件 item_row.xml 并添加以下内容 −
<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" app:cardElevation="2dp" app:cardUseCompatPadding="true"> <TextView android:id="@+id/textViewItem" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:textColor="@android:color/holo_blue_bright" android:textStyle="bold" /> </androidx.cardview.widget.CardView>
步骤 6 − 创建一个布局资源文件 item_loading.xml 并添加以下内容 −
<?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="match_parent" android:orientation="vertical"> <ProgressBar android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:indeterminate="true" android:paddingLeft="8dp" android:paddingRight="8dp" /> </LinearLayout>
步骤 7 − 将以下代码添加到 androidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
让我们尝试运行您的应用程序。我假设您已将您的实际 Android 移动设备连接到您的计算机。要从 Android Studio 运行应用程序,请打开您的一个项目活动文件,然后点击工具栏中的运行图标 。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕
广告