📜  Android中的无尽RecyclerView

📅  最后修改于: 2021-05-10 16:34:22             🧑  作者: Mango

在本文中,我们将了解如何在Android Studio中构建无尽的RecyclerView 它主要用于设计用户界面,从而可以很好地控制android应用程序的列表和网格。我们可以使用RecyclerView来实现水平和垂直布局。在这里,我们将创建一个带有更多加载选项的RecyclerView 。下面显示了一个示例视频,以了解我们将在本文中做些什么。请注意,我们将使用Java作为编程语言。

分步实施

步骤1:创建一个新项目

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

步骤2:使用activity_main.xml文件

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

XML


  
    
    
  


XML


  
    
    
  


XML


  
    
    
  


Java
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 java.util.List;
  
public class RecylerViewAdapter extends RecyclerView.Adapter {
      
    private final int VIEW_TYPE_ITEM = 0;
    private final int VIEW_TYPE_LOADING = 1;
    private List mItemList;
  
    public RecylerViewAdapter(List itemList) {
        mItemList = itemList;
    }
  
    // Based on the View type we are instantiating the 
    // ViewHolder in the onCreateViewHolder() method
    @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);
        }
    }
    
    // Inside the onBindViewHolder() method we 
    // are checking the type of ViewHolder
    // instance and populating the row accordingly
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ItemViewHolder) {
            populateItemRows((ItemViewHolder) holder, position);
        } else if (holder instanceof LoadingviewHolder) {
            showLoadingView((LoadingviewHolder) holder, position);
        }
    }
  
    // getItemCount() method returns the size of the list
    @Override
    public int getItemCount() {
        return mItemList == null ? 0 : mItemList.size();
    }
  
    // getItemViewType() method is the method where we check each element 
    // of the list. If the element is NULL we set the view type as 1 else 0
    public int getItemViewType(int position) {
        return mItemList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
    }
      
    public class ItemViewHolder extends RecyclerView.ViewHolder {
        TextView tvItem;
        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            tvItem = itemView.findViewById(R.id.tvItem);
        }
    }
  
    private class LoadingviewHolder extends RecyclerView.ViewHolder {
        ProgressBar progressBar;
        public LoadingviewHolder(@NonNull View itemView) {
            super(itemView);
            progressBar = itemView.findViewById(R.id.progressbar);
        }
    }
  
    private void showLoadingView(LoadingviewHolder viewHolder, int position) {
        // Progressbar would be displayed
    }
      
    private void populateItemRows(ItemViewHolder viewHolder, int position) {
        String item = mItemList.get(position);
        viewHolder.tvItem.setText(item);
    }
}


Java
import android.os.Bundle;
import android.os.Handler;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    RecyclerView recyclerView;
    RecylerViewAdapter recylerViewAdapter;
    ArrayList 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);
  
        // Following three methods have 
        // been implemented in this class.
        populateData();
        initAdapter();
        initScrollListener();
    }
   
    // PopulateData() method shows after how many items load more option 
    // should be made available. In our case, i have taken 20 items
    private void populateData() {
        int i = 0;
        while (i < 20) {
            rowsArrayList.add("ITEM " + i);
            i++;
        }
    }
      
    // initAdapter() method initiates the RecyclerViewAdapter
    private void initAdapter() {
        recylerViewAdapter = new RecylerViewAdapter(rowsArrayList);
        recyclerView.setAdapter(recylerViewAdapter);
    }
  
    // initScrollListener() method is the method where we are checking 
    // the scrolled state of the RecyclerView and if bottom-most is visible
    // we are showing the loading view and populating the next list
    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;
            }
        }
        }
        }
        );
    }
  
    // LoadMore() method is used to implement
    // the functionality of load more
    private void loadMore() {
        rowsArrayList.add(null);
        recylerViewAdapter.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();
                recylerViewAdapter.notifyItemRemoved(scrollPosition);
                int currentSize = scrollPosition;
                  
                // Next load more option is to be shown after every 10 items.
                int nextLimit = currentSize + 10;
  
                while (currentSize - 1 < nextLimit) {
                    rowsArrayList.add("Item " + currentSize);
                    currentSize++;
                }
  
                recylerViewAdapter.notifyDataSetChanged();
                isLoading = false;
            }
        }, 2000);
    }
}


步骤3:创建一个新的布局资源文件

创建一个新的 布局资源文件,名称为item_row.xml 。要创建新的布局资源文件,请导航至res> layout 。右键单击布局文件夹,然后单击“新建” ,然后单击“布局资源文件” ,将打开一个对话框,为您的布局资源文件添加一个名称,然后单击“确定”按钮。创建新的布局资源文件。请遵循以下图像:

步骤4:使用item_row.xml文件

转到布局> item_row.xml文件,然后将以下代码添加到该文件中。此处定义了RecyclerView的行的布局。

XML格式



  
    
    
  

步骤5:再次创建一个新的布局资源文件

创建一个名为item_loading.xml的新布局资源文件。要创建新的布局资源文件,请导航至res> layout 。右键单击布局文件夹,然后单击“新建” ,然后单击“布局资源文件” ,将打开一个对话框,为您的布局资源文件添加一个名称,然后单击“确定”按钮。创建新的布局资源文件。请遵循以下图像:

步骤6:使用item_loading.xml文件

转到布局> item_loading.xml文件,然后将以下代码添加到该文件中。此处定义了加载视图的布局。

XML格式



  
    
    
  

步骤7:为RecyclerView创建一个适配器类

为RecyclerView创建一个适配器类,名称为RecyclerViewAdapter。要创建适配器类,您必须遵循以下图像:

在适配器类中添加名称后,按Enter键。您的RecycleviewAdapter。 Java文件已创建。

步骤8:使用RecyclerViewAdapter。 Java文件

转到RecyclerViewAdapter。 Java文件,并将下面给出的代码添加到该文件中。在代码内部添加了注释,以更详细地了解代码。

Java

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 java.util.List;
  
public class RecylerViewAdapter extends RecyclerView.Adapter {
      
    private final int VIEW_TYPE_ITEM = 0;
    private final int VIEW_TYPE_LOADING = 1;
    private List mItemList;
  
    public RecylerViewAdapter(List itemList) {
        mItemList = itemList;
    }
  
    // Based on the View type we are instantiating the 
    // ViewHolder in the onCreateViewHolder() method
    @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);
        }
    }
    
    // Inside the onBindViewHolder() method we 
    // are checking the type of ViewHolder
    // instance and populating the row accordingly
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ItemViewHolder) {
            populateItemRows((ItemViewHolder) holder, position);
        } else if (holder instanceof LoadingviewHolder) {
            showLoadingView((LoadingviewHolder) holder, position);
        }
    }
  
    // getItemCount() method returns the size of the list
    @Override
    public int getItemCount() {
        return mItemList == null ? 0 : mItemList.size();
    }
  
    // getItemViewType() method is the method where we check each element 
    // of the list. If the element is NULL we set the view type as 1 else 0
    public int getItemViewType(int position) {
        return mItemList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
    }
      
    public class ItemViewHolder extends RecyclerView.ViewHolder {
        TextView tvItem;
        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            tvItem = itemView.findViewById(R.id.tvItem);
        }
    }
  
    private class LoadingviewHolder extends RecyclerView.ViewHolder {
        ProgressBar progressBar;
        public LoadingviewHolder(@NonNull View itemView) {
            super(itemView);
            progressBar = itemView.findViewById(R.id.progressbar);
        }
    }
  
    private void showLoadingView(LoadingviewHolder viewHolder, int position) {
        // Progressbar would be displayed
    }
      
    private void populateItemRows(ItemViewHolder viewHolder, int position) {
        String item = mItemList.get(position);
        viewHolder.tvItem.setText(item);
    }
}

步骤9:使用MainActivity。 Java文件

转到MainActivity。 Java文件以及下面对该文件给出的代码。在MainActivity中。我们将实例化上面的Adapter的Java类。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.os.Handler;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    RecyclerView recyclerView;
    RecylerViewAdapter recylerViewAdapter;
    ArrayList 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);
  
        // Following three methods have 
        // been implemented in this class.
        populateData();
        initAdapter();
        initScrollListener();
    }
   
    // PopulateData() method shows after how many items load more option 
    // should be made available. In our case, i have taken 20 items
    private void populateData() {
        int i = 0;
        while (i < 20) {
            rowsArrayList.add("ITEM " + i);
            i++;
        }
    }
      
    // initAdapter() method initiates the RecyclerViewAdapter
    private void initAdapter() {
        recylerViewAdapter = new RecylerViewAdapter(rowsArrayList);
        recyclerView.setAdapter(recylerViewAdapter);
    }
  
    // initScrollListener() method is the method where we are checking 
    // the scrolled state of the RecyclerView and if bottom-most is visible
    // we are showing the loading view and populating the next list
    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;
            }
        }
        }
        }
        );
    }
  
    // LoadMore() method is used to implement
    // the functionality of load more
    private void loadMore() {
        rowsArrayList.add(null);
        recylerViewAdapter.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();
                recylerViewAdapter.notifyItemRemoved(scrollPosition);
                int currentSize = scrollPosition;
                  
                // Next load more option is to be shown after every 10 items.
                int nextLimit = currentSize + 10;
  
                while (currentSize - 1 < nextLimit) {
                    rowsArrayList.add("Item " + currentSize);
                    currentSize++;
                }
  
                recylerViewAdapter.notifyDataSetChanged();
                isLoading = false;
            }
        }, 2000);
    }
}

输出: