📜  如何使用Volley在Android RecyclerView中实现分页?

📅  最后修改于: 2021-05-08 19:46:17             🧑  作者: Mango

分页是最重要的因素之一,它有助于减少应用程序内的加载时间并提高以列表形式表示的数据的性能。在本文中,我们将介绍如何在Android RecyclerView中添加分页。为了从API获取数据,我们将使用Volley库。

什么是分页?

分页是根据需求加载数据,而不是一次加载完整数据。因此,这有助于减少从API加载数据的时间,并提高应用程序的性能。

在数据列表中使用分页有什么好处?

很多情况下,我们不得不一次在列表视图或回收者视图中加载大量数据。因此,如果我们一次加载所有数据,则将花费一些时间来加载数据,这将增加我们的Recycler View的加载时间。分页将为您提供支持,我们可以以块的形式加载数据,因此这将防止我们的回收视图降低其性能,并且数据加载会更快。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在其中我们将在Android RecyclerView中显示数据列表,并在RecyclerView中添加分页以加载数据。下面提供了一个示例视频,以使您对我们在本文中将要做的事情有个大概的了解。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:在您的build.gradle文件中添加以下依赖项

以下是Volley的依赖关系,我们将使用它们来从API获取数据。要添加此依赖关系,请导航至应用程序> Gradle脚本> build.gradle(app),然后在“依赖关系”部分添加以下依赖关系。我们已将Picasso依赖项用于从URL加载图像。

添加此依赖项后,同步您的项目,现在移至AndroidManifest.xml部分。

步骤3:在AndroidManifest.xml文件中向Internet添加权限

导航至应用程序> AndroidManifest.xml,然后将以下代码添加到其中。

XML


XML



  
    
    
          
        
        
          
        
        
    
      


Java
public class UserModal {
    // variables for our first name, 
    // last name, email and avatar
    private String first_name;
    private String last_name;
    private String email;
    private String avatar;
  
    public String getFirst_name() {
        return first_name;
    }
  
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
  
    public String getLast_name() {
        return last_name;
    }
  
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
  
    public String getEmail() {
        return email;
    }
  
    public void setEmail(String email) {
        this.email = email;
    }
  
    public String getAvatar() {
        return avatar;
    }
  
    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }
  
    public UserModal(String first_name, String last_name, String email, String avatar) {
        this.first_name = first_name;
        this.last_name = last_name;
        this.email = email;
        this.avatar = avatar;
    }
}


XML


  
    
  
        
        
  
        
        
  
        
        
  
        
        
  
    
  


Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class UserRVAdapter extends RecyclerView.Adapter {
     
    // variable for our array list and context.
    private ArrayList userModalArrayList;
    private Context context;
  
    // creating a constructor.
    public UserRVAdapter(ArrayList userModalArrayList, Context context) {
        this.userModalArrayList = userModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // inflating our layout file on below line.
        View view = LayoutInflater.from(context).inflate(R.layout.user_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
          
        // getting data from our array list in our modal class.
        UserModal userModal = userModalArrayList.get(position);
          
        // on below line we are setting data to our text view.
        holder.firstNameTV.setText(userModal.getFirst_name());
        holder.lastNameTV.setText(userModal.getLast_name());
        holder.emailTV.setText(userModal.getEmail());
          
        // on below line we are loading our image 
        // from url in our image view using picasso.
        Picasso.get().load(userModal.getAvatar()).into(holder.userIV);
    }
  
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return userModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating a variable for our text view and image view.
        private TextView firstNameTV, lastNameTV, emailTV;
        private ImageView userIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
              
            // initializing our variables.
            firstNameTV = itemView.findViewById(R.id.idTVFirstName);
            lastNameTV = itemView.findViewById(R.id.idTVLastName);
            emailTV = itemView.findViewById(R.id.idTVEmail);
            userIV = itemView.findViewById(R.id.idIVUser);
        }
    }
}


Java
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
  
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating a variable for our array list, adapter class,
    // recycler view, progressbar, nested scroll view
    private ArrayList userModalArrayList;
    private UserRVAdapter userRVAdapter;
    private RecyclerView userRV;
    private ProgressBar loadingPB;
    private NestedScrollView nestedSV;
      
    // creating a variable for our page and limit as 2
    // as our api is having highest limit as 2 so 
    // we are setting a limit = 2
    int page = 0, limit = 2;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // creating a new array list.
        userModalArrayList = new ArrayList<>();
          
        // initializing our views.
        userRV = findViewById(R.id.idRVUsers);
        loadingPB = findViewById(R.id.idPBLoading);
        nestedSV = findViewById(R.id.idNestedSV);
          
        // calling a method to load our api.
        getDataFromAPI(page, limit);
          
        // adding on scroll change listener method for our nested scroll view.
        nestedSV.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                // on scroll change we are checking when users scroll as bottom.
                if (scrollY == v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight()) {
                    // in this method we are incrementing page number,
                    // making progress bar visible and calling get data method.
                    page++;
                    loadingPB.setVisibility(View.VISIBLE);
                    getDataFromAPI(page, limit);
                }
            }
        });
    }
  
    private void getDataFromAPI(int page, int limit) {
        if (page > limit) {
            // checking if the page number is greater than limit.
            // displaying toast message in this case when page>limit.
            Toast.makeText(this, "That's all the data..", Toast.LENGTH_SHORT).show();
              
            // hiding our progress bar.
            loadingPB.setVisibility(View.GONE);
            return;
        }
        // creating a string variable for url .
        String url = "https://reqres.in/api/users?page=" + page;
          
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
          
        // creating a variable for our json object request and passing our url to it.
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                      
                    // on below line we are extracting data from our json array.
                    JSONArray dataArray = response.getJSONArray("data");
                      
                    // passing data from our json array in our array list.
                    for (int i = 0; i < dataArray.length(); i++) {
                        JSONObject jsonObject = dataArray.getJSONObject(i);
                          
                        // on below line we are extracting data from our json object.
                        userModalArrayList.add(new UserModal(jsonObject.getString("first_name"), jsonObject.getString("last_name"), jsonObject.getString("email"), jsonObject.getString("avatar")));
                          
                        // passing array list to our adapter class.
                        userRVAdapter = new UserRVAdapter(userModalArrayList, MainActivity.this);
                          
                        // setting layout manager to our recycler view.
                        userRV.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                          
                        // setting adapter to our recycler view.
                        userRV.setAdapter(userRVAdapter);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // handling on error listener method.
                Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show();
            }
        });
        // calling a request queue method 
        // and passing our json object
        queue.add(jsonObjectRequest);
    }
}


步骤4:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。

XML格式




  
    
    
          
        
        
          
        
        
    
      

第5步:创建用于存储数据的Modal类

为了存储我们的数据,我们必须创建一个新的Java类。要创建新的Java类,请导航至应用程序> Java >应用程序的包名称>右键单击它>新建> Java类,并将其命名为UserModal,然后将以下代码添加到其中。在代码内部添加了注释,以更详细地了解代码。

Java

public class UserModal {
    // variables for our first name, 
    // last name, email and avatar
    private String first_name;
    private String last_name;
    private String email;
    private String avatar;
  
    public String getFirst_name() {
        return first_name;
    }
  
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
  
    public String getLast_name() {
        return last_name;
    }
  
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
  
    public String getEmail() {
        return email;
    }
  
    public void setEmail(String email) {
        this.email = email;
    }
  
    public String getAvatar() {
        return avatar;
    }
  
    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }
  
    public UserModal(String first_name, String last_name, String email, String avatar) {
        this.first_name = first_name;
        this.last_name = last_name;
        this.email = email;
        this.avatar = avatar;
    }
}

第6步:为我们的RecyclerView的每个项目创建一个布局文件

导航到应用程序> res>布局>右键单击它>新建>布局资源文件,并将文件名指定为user_rv_item,然后将以下代码添加到其中。在代码中添加了注释,以便更详细地了解。

XML格式



  
    
  
        
        
  
        
        
  
        
        
  
        
        
  
    
  

步骤7:创建用于将数据设置到我们的RecyclerView项的Adapter类

要创建新的适配器类,请导航至应用程序> Java >应用程序的包名称>右键单击它>新建> Java类,并将其命名为UserRVAdapter,然后将以下代码添加到其中。

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class UserRVAdapter extends RecyclerView.Adapter {
     
    // variable for our array list and context.
    private ArrayList userModalArrayList;
    private Context context;
  
    // creating a constructor.
    public UserRVAdapter(ArrayList userModalArrayList, Context context) {
        this.userModalArrayList = userModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // inflating our layout file on below line.
        View view = LayoutInflater.from(context).inflate(R.layout.user_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
          
        // getting data from our array list in our modal class.
        UserModal userModal = userModalArrayList.get(position);
          
        // on below line we are setting data to our text view.
        holder.firstNameTV.setText(userModal.getFirst_name());
        holder.lastNameTV.setText(userModal.getLast_name());
        holder.emailTV.setText(userModal.getEmail());
          
        // on below line we are loading our image 
        // from url in our image view using picasso.
        Picasso.get().load(userModal.getAvatar()).into(holder.userIV);
    }
  
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return userModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating a variable for our text view and image view.
        private TextView firstNameTV, lastNameTV, emailTV;
        private ImageView userIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
              
            // initializing our variables.
            firstNameTV = itemView.findViewById(R.id.idTVFirstName);
            lastNameTV = itemView.findViewById(R.id.idTVLastName);
            emailTV = itemView.findViewById(R.id.idTVEmail);
            userIV = itemView.findViewById(R.id.idIVUser);
        }
    }
}

步骤8:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
  
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating a variable for our array list, adapter class,
    // recycler view, progressbar, nested scroll view
    private ArrayList userModalArrayList;
    private UserRVAdapter userRVAdapter;
    private RecyclerView userRV;
    private ProgressBar loadingPB;
    private NestedScrollView nestedSV;
      
    // creating a variable for our page and limit as 2
    // as our api is having highest limit as 2 so 
    // we are setting a limit = 2
    int page = 0, limit = 2;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // creating a new array list.
        userModalArrayList = new ArrayList<>();
          
        // initializing our views.
        userRV = findViewById(R.id.idRVUsers);
        loadingPB = findViewById(R.id.idPBLoading);
        nestedSV = findViewById(R.id.idNestedSV);
          
        // calling a method to load our api.
        getDataFromAPI(page, limit);
          
        // adding on scroll change listener method for our nested scroll view.
        nestedSV.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                // on scroll change we are checking when users scroll as bottom.
                if (scrollY == v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight()) {
                    // in this method we are incrementing page number,
                    // making progress bar visible and calling get data method.
                    page++;
                    loadingPB.setVisibility(View.VISIBLE);
                    getDataFromAPI(page, limit);
                }
            }
        });
    }
  
    private void getDataFromAPI(int page, int limit) {
        if (page > limit) {
            // checking if the page number is greater than limit.
            // displaying toast message in this case when page>limit.
            Toast.makeText(this, "That's all the data..", Toast.LENGTH_SHORT).show();
              
            // hiding our progress bar.
            loadingPB.setVisibility(View.GONE);
            return;
        }
        // creating a string variable for url .
        String url = "https://reqres.in/api/users?page=" + page;
          
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
          
        // creating a variable for our json object request and passing our url to it.
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                      
                    // on below line we are extracting data from our json array.
                    JSONArray dataArray = response.getJSONArray("data");
                      
                    // passing data from our json array in our array list.
                    for (int i = 0; i < dataArray.length(); i++) {
                        JSONObject jsonObject = dataArray.getJSONObject(i);
                          
                        // on below line we are extracting data from our json object.
                        userModalArrayList.add(new UserModal(jsonObject.getString("first_name"), jsonObject.getString("last_name"), jsonObject.getString("email"), jsonObject.getString("avatar")));
                          
                        // passing array list to our adapter class.
                        userRVAdapter = new UserRVAdapter(userModalArrayList, MainActivity.this);
                          
                        // setting layout manager to our recycler view.
                        userRV.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                          
                        // setting adapter to our recycler view.
                        userRV.setAdapter(userRVAdapter);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // handling on error listener method.
                Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show();
            }
        });
        // calling a request queue method 
        // and passing our json object
        queue.add(jsonObjectRequest);
    }
}

现在运行您的应用程序,并查看该应用程序的输出。

输出: