如何在Android中使用RecyclerView实现无限列表?
此示例演示了如何在Android中使用RecyclerView实现无限列表。
步骤1 - 在Android Studio中创建一个新项目,转到文件⇒新建项目,并填写所有必要信息以创建新项目。
在build.gradle (Module: app)中添加以下依赖项:
implementation 'com.android.support:cardview-v7:28.0.0' implementation 'com.android.support:recyclerview-v7:28.0.0'
步骤2 - 将以下代码添加到res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
步骤3 - 将以下代码添加到src/MainActivity.java。
import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.os.Handler; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; RecyclerViewAdapter recyclerViewAdapter; ArrayList<String>rowsArrayList = new ArrayList<>(); boolean isLoading = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recyclerView); populateData(); initAdapter(); initScrollListener(); } private void populateData() { for (int i = 0; i < 10; i++) { rowsArrayList.add("Number " + i); } } private void initAdapter() { recyclerViewAdapter = new RecyclerViewAdapter(rowsArrayList); recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); recyclerView.setAdapter(recyclerViewAdapter); } private void initScrollListener() { recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); if (!isLoading) { if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == rowsArrayList.size() - 1) { //bottom of list! loadMore(); isLoading = true; } } } }); } private void loadMore() { rowsArrayList.add(null); recyclerViewAdapter.notifyItemInserted(rowsArrayList.size() - 1); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { rowsArrayList.remove(rowsArrayList.size() - 1); int scrollPosition = rowsArrayList.size(); recyclerViewAdapter.notifyItemRemoved(scrollPosition); int currentSize = scrollPosition; int nextLimit = currentSize + 10; while (currentSize - 1 < nextLimit) { rowsArrayList.add("Number " + currentSize); currentSize++; } recyclerViewAdapter.notifyDataSetChanged(); isLoading = false; } }, 2000); } }
步骤4 - 创建一个新的Java类(RecyclerViewAdapter.java)并添加以下代码:
package app.com.sample; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private final int VIEW_TYPE_ITEM = 0; private List<String> mItemList; RecyclerViewAdapter(List<String> itemList) { mItemList = itemList; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if (viewType == VIEW_TYPE_ITEM) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false); return new ItemViewHolder(view); } else { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading, parent, false); return new LoadingViewHolder(view); } } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) { if (viewHolder instanceof ItemViewHolder) { populateItemRows((ItemViewHolder) viewHolder, position); } else if (viewHolder instanceof LoadingViewHolder) { showLoadingView((LoadingViewHolder) viewHolder, position); } } @Override public int getItemCount() { return mItemList == null ? 0 : mItemList.size(); } @Override public int getItemViewType(int position) { int VIEW_TYPE_LOADING = 1; return mItemList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM; } private class ItemViewHolder extends RecyclerView.ViewHolder { TextView tvItem; ItemViewHolder(@NonNull View itemView) { super(itemView); tvItem = itemView.findViewById(R.id.textViewItem); } } private class LoadingViewHolder extends RecyclerView.ViewHolder { ProgressBar progressBar; LoadingViewHolder(@NonNull View itemView) { super(itemView); progressBar = itemView.findViewById(R.id.progressBar); } } private void showLoadingView(LoadingViewHolder viewHolder, int position) { } private void populateItemRows(ItemViewHolder viewHolder, int position) { String item = mItemList.get(position); viewHolder.tvItem.setText(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" /> </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="app.com.sample"> <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运行应用程序,请打开您的项目活动文件之一,然后单击工具栏中的运行 图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕:
点击这里下载项目代码。
广告