📜  Android RecyclerView 在 Scroll 上加载更多示例

📅  最后修改于: 2022-05-13 01:54:35.276000             🧑  作者: Mango

Android RecyclerView 在 Scroll 上加载更多示例

许多应用程序以列表的形式显示大量数据。这些数据太多以至于不能一次加载。如果我们一次加载这些数据,那么它可能需要很多加载时间并降低我们的 RecyclerView 的性能。所以为了解决这个问题,我们通常将数据分块加载并一次显示。在本文中,我们将通过显示一个 ProgressBar 并在无限列表中加载数据来看看加载这些数据。

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

我们将构建一个简单的应用程序,我们将在其中显示无限列表,并在下面的 ProgressBar 的帮助下加载数据。我们将调用相同的方法将数据添加到我们的 ArrayList。下面给出了一个示例 GIF,以了解我们将在本文中做什么。请注意,我们将使用Java语言来实现这个项目。

Android RecyclerView 在滚动上加载更多示例示例 GIF

分步实施

第 1 步:创建一个新项目

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



第 2 步:在 build.gradle 文件中添加以下依赖项并在清单文件中允许 Internet 权限

下面是我们将用来从 API 获取数据的 Volley 的依赖项。要添加此依赖项,请导航到app > Gradle Scripts > build.gradle(app)并在依赖项部分添加以下依赖项。我们已经使用 Picasso 依赖项从 URL 加载图像。

// below line is used for volley library
implementation ‘com.android.volley:volley:1.1.1’

// below line is used for image loading library
implementation ‘com.squareup.picasso:picasso:2.71828’

在清单文件中添加 Internet 权限。

步骤 3:使用 activity_main.xml 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件中。下面是activity_main.xml文件的代码。

XML


  
    
    
  
        
        
  
        
        
    
  


Java
public class CourseModal {
  
    // variables for our course name,
    // description and duration.
    private String courseName;
    private String courseModes;
    private String courseTracks;
    private String courseImg;
  
    // constructor class.
    public CourseModal(String courseName, String courseModes, String courseTracks, String courseImg) {
        this.courseName = courseName;
        this.courseModes = courseModes;
        this.courseTracks = courseTracks;
        this.courseImg = courseImg;
    }
  
    // getter and setter methods.
    public String getCourseImg() {
        return courseImg;
    }
  
    public void setCourseImg(String courseImg) {
        this.courseImg = courseImg;
    }
  
    public String getCourseName() {
        return courseName;
    }
  
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
  
    public String getcourseModes() {
        return courseModes;
    }
  
    public void setcourseModes(String courseModes) {
        this.courseModes = courseModes;
    }
  
    public String getcourseTracks() {
        return courseTracks;
    }
  
    public void setcourseTracks(String courseTracks) {
        this.courseTracks = courseTracks;
    }
}


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 CourseRVAdapter extends RecyclerView.Adapter {
      
    private Context context;
    private ArrayList courseModalArrayList;
  
    // creating a constructor class.
    public CourseRVAdapter(Context context, ArrayList courseModalArrayList) {
        this.context = context;
        this.courseModalArrayList = courseModalArrayList;
    }
  
    @NonNull
    @Override
    public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // passing our layout file for displaying our card item
        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_rv_item, parent, false));
  
    }
  
    @Override
    public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {
        // setting data to our text views from our modal class.
        CourseModal courses = courseModalArrayList.get(position);
        holder.courseNameTV.setText(courses.getCourseName());
        holder.courseTracksTV.setText(courses.getcourseTracks());
        holder.courseModesTV.setText(courses.getcourseModes());
        Picasso.get().load(courses.getCourseImg()).into(holder.courseIV);
    }
  
    @Override
    public int getItemCount() {
        return courseModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our text views.
        private final TextView courseNameTV;
        private final TextView courseTracksTV;
        private final TextView courseModesTV;
        private final ImageView courseIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our text views.
            courseIV = itemView.findViewById(R.id.idIVCourse);
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseTracksTV = itemView.findViewById(R.id.idTVCourseDuration);
            courseModesTV = itemView.findViewById(R.id.idTVCourseDescription);
        }
    }
}


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.JsonArrayRequest;
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 variables for our UI components.
    int count = 0;
    String url = "https://jsonkeeper.com/b/WO6S";
    private ArrayList courseArrayList;
    private RecyclerView courseRV;
    private CourseRVAdapter courseRVAdapter;
    private ProgressBar loadingPB;
    private NestedScrollView nestedSV;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses);
        loadingPB = findViewById(R.id.idPBLoading);
        nestedSV = findViewById(R.id.idNestedSV);
          
        // initializing our array list.
        courseArrayList = new ArrayList<>();
          
        // calling a method to add data to our array list.
        getData();
          
        // on below line we are setting layout manger to our recycler view.
        LinearLayoutManager manager = new LinearLayoutManager(this);
        courseRV.setLayoutManager(manager);
        // 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.
                    count++;
                    // on below line we are making our progress bar visible.
                    loadingPB.setVisibility(View.VISIBLE);
                    if (count < 20) {
                        // on below line we are again calling
                        // a method to load data in our array list.
                        getData();
                    }
                }
            }
        });
    }
  
    private void getData() {
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        // in this case the data we are getting is in the form
        // of array so we are making a json array request.
        // below is the line where we are making an json array
        // request and then extracting data from each json object.
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONArray response) {
  
                courseRV.setVisibility(View.VISIBLE);
                for (int i = 0; i < response.length(); i++) {
                    // creating a new json object and
                    // getting each object from our json array.
                    try {
                        // we are getting each json object.
                        JSONObject responseObj = response.getJSONObject(i);
  
                        // now we get our response from API in json object format.
                        // in below line we are extracting a string with
                        // its key value from our json object.
                        // similarly we are extracting all the strings from our json object.
                        String courseName = responseObj.getString("courseName");
                        String courseTracks = responseObj.getString("courseTracks");
                        String courseMode = responseObj.getString("courseMode");
                        String courseImageURL = responseObj.getString("courseimg");
                        courseArrayList.add(new CourseModal(courseName, courseMode, courseTracks, courseImageURL));
                          
                        // on below line we are adding our array list to our adapter class.
                        courseRVAdapter = new CourseRVAdapter(MainActivity.this, courseArrayList);
                          
                        // on below line we are setting 
                        // adapter to our recycler view.
                        courseRV.setAdapter(courseRVAdapter);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(jsonArrayRequest);
    }
}


第 4 步:使用模态类

导航到应用程序 > Java > 您应用程序的包名称 > 右键单击它 > 新建 > Java类并将其命名为CourseModal并将以下代码添加到其中。



Java

public class CourseModal {
  
    // variables for our course name,
    // description and duration.
    private String courseName;
    private String courseModes;
    private String courseTracks;
    private String courseImg;
  
    // constructor class.
    public CourseModal(String courseName, String courseModes, String courseTracks, String courseImg) {
        this.courseName = courseName;
        this.courseModes = courseModes;
        this.courseTracks = courseTracks;
        this.courseImg = courseImg;
    }
  
    // getter and setter methods.
    public String getCourseImg() {
        return courseImg;
    }
  
    public void setCourseImg(String courseImg) {
        this.courseImg = courseImg;
    }
  
    public String getCourseName() {
        return courseName;
    }
  
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
  
    public String getcourseModes() {
        return courseModes;
    }
  
    public void setcourseModes(String courseModes) {
        this.courseModes = courseModes;
    }
  
    public String getcourseTracks() {
        return courseTracks;
    }
  
    public void setcourseTracks(String courseTracks) {
        this.courseTracks = courseTracks;
    }
}

第 5 步:为我们的 RecyclerView 项创建布局文件

导航到应用程序 > res > 布局 > 右键单击它 > 新建 > 布局资源文件并将其命名为course_rv_item并将以下代码添加到其中。

XML



  
    
  
        
        
          
        
  
            
            
              
            
            
              
            
            
        
  
    
      

第 6 步:创建用于设置数据的适配器类

同样,创建另一个Java类并将其命名为CourseRVAdapter并向其添加以下代码。代码中添加了注释,以便更详细地了解。

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 CourseRVAdapter extends RecyclerView.Adapter {
      
    private Context context;
    private ArrayList courseModalArrayList;
  
    // creating a constructor class.
    public CourseRVAdapter(Context context, ArrayList courseModalArrayList) {
        this.context = context;
        this.courseModalArrayList = courseModalArrayList;
    }
  
    @NonNull
    @Override
    public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // passing our layout file for displaying our card item
        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_rv_item, parent, false));
  
    }
  
    @Override
    public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {
        // setting data to our text views from our modal class.
        CourseModal courses = courseModalArrayList.get(position);
        holder.courseNameTV.setText(courses.getCourseName());
        holder.courseTracksTV.setText(courses.getcourseTracks());
        holder.courseModesTV.setText(courses.getcourseModes());
        Picasso.get().load(courses.getCourseImg()).into(holder.courseIV);
    }
  
    @Override
    public int getItemCount() {
        return courseModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our text views.
        private final TextView courseNameTV;
        private final TextView courseTracksTV;
        private final TextView courseModesTV;
        private final ImageView courseIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our text views.
            courseIV = itemView.findViewById(R.id.idIVCourse);
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseTracksTV = itemView.findViewById(R.id.idTVCourseDuration);
            courseModesTV = itemView.findViewById(R.id.idTVCourseDescription);
        }
    }
}

第 7 步:使用MainActivity。 Java文件

转到主活动。 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.JsonArrayRequest;
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 variables for our UI components.
    int count = 0;
    String url = "https://jsonkeeper.com/b/WO6S";
    private ArrayList courseArrayList;
    private RecyclerView courseRV;
    private CourseRVAdapter courseRVAdapter;
    private ProgressBar loadingPB;
    private NestedScrollView nestedSV;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses);
        loadingPB = findViewById(R.id.idPBLoading);
        nestedSV = findViewById(R.id.idNestedSV);
          
        // initializing our array list.
        courseArrayList = new ArrayList<>();
          
        // calling a method to add data to our array list.
        getData();
          
        // on below line we are setting layout manger to our recycler view.
        LinearLayoutManager manager = new LinearLayoutManager(this);
        courseRV.setLayoutManager(manager);
        // 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.
                    count++;
                    // on below line we are making our progress bar visible.
                    loadingPB.setVisibility(View.VISIBLE);
                    if (count < 20) {
                        // on below line we are again calling
                        // a method to load data in our array list.
                        getData();
                    }
                }
            }
        });
    }
  
    private void getData() {
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        // in this case the data we are getting is in the form
        // of array so we are making a json array request.
        // below is the line where we are making an json array
        // request and then extracting data from each json object.
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONArray response) {
  
                courseRV.setVisibility(View.VISIBLE);
                for (int i = 0; i < response.length(); i++) {
                    // creating a new json object and
                    // getting each object from our json array.
                    try {
                        // we are getting each json object.
                        JSONObject responseObj = response.getJSONObject(i);
  
                        // now we get our response from API in json object format.
                        // in below line we are extracting a string with
                        // its key value from our json object.
                        // similarly we are extracting all the strings from our json object.
                        String courseName = responseObj.getString("courseName");
                        String courseTracks = responseObj.getString("courseTracks");
                        String courseMode = responseObj.getString("courseMode");
                        String courseImageURL = responseObj.getString("courseimg");
                        courseArrayList.add(new CourseModal(courseName, courseMode, courseTracks, courseImageURL));
                          
                        // on below line we are adding our array list to our adapter class.
                        courseRVAdapter = new CourseRVAdapter(MainActivity.this, courseArrayList);
                          
                        // on below line we are setting 
                        // adapter to our recycler view.
                        courseRV.setAdapter(courseRVAdapter);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(jsonArrayRequest);
    }
}

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

输出: