Android recyclerview StaggedGridLayoutManager加载更多进度条

Android recyclerview StaggedGridLayoutManager加载更多进度条,android,android-recyclerview,android-progressbar,endlessscroll,Android,Android Recyclerview,Android Progressbar,Endlessscroll,我在布局中有一个回收视图: <?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:baselineAligned="false

我在布局中有一个回收视图

<?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:baselineAligned="false"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/advertising_list_view_right"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:divider="@null"
        android:dividerHeight="0dp"
        android:scrollbars="none" />

    <TextView
        android:id="@+id/empty_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="@string/no_records"
        android:visibility="gone" />

</LinearLayout>

我的CustomAdapter是:

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {

private final List<Ad> dataList;
private final Context context;

CustomAdapter(Context context, List<Ad> dataList) {
    this.context = context;
    this.dataList = dataList;
}

class CustomViewHolder extends RecyclerView.ViewHolder {

    final View mView;

    private final TextView adTitle;
    private final TextView adLocation;
    private final TextView adPrice;
    private final ImageView coverImage;

    CustomViewHolder(View itemView) {
        super(itemView);
        mView = itemView;

        adTitle = mView.findViewById(R.id.title);
        adLocation = mView.findViewById(R.id.text_view_key_4);
        adPrice = mView.findViewById(R.id.price_text_view);
        coverImage = mView.findViewById(R.id.company_image_view);
        coverImage.layout(0, 0, 0, 0);
    }
}

@NonNull
@Override
public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
    View view = layoutInflater.inflate(R.layout.advertising_list_item, parent, false);
    return new CustomViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
    holder.adTitle.setText(dataList.get(position).getTitle());
    holder.adLocation.setText(dataList.get(position).getParish());
    if (dataList.get(position).getPrice().length() == 0) {
        holder.adPrice.setText(R.string.agreement);
    } else {
        holder.adPrice.setText(dataList.get(position).getPrice() + " تومان");
    }

    GlideApp.with(context)
            .load(dataList.get(position).getPicture())
            .error(R.drawable.default_pic)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .override(dataList.get(position).getPictureWidth(), dataList.get(position).getPictureHeight())
            .placeholder(R.drawable.default_pic)
            .centerCrop()
            .into(holder.coverImage);


}

@Override
public int getItemCount() {
    return dataList.size();
}
公共类CustomAdapter扩展了RecyclerView.Adapter{ 私人最终清单数据清单; 私人最终语境; CustomAdapter(上下文、列表数据列表){ this.context=上下文; this.dataList=dataList; } 类CustomViewHolder扩展了RecyclerView.ViewHolder{ 最终视图mView; 私有最终文本视图adTitle; 私有最终文本视图位置; 私人最终文本视图adPrice; 私人最终图像查看封面图像; CustomViewHolder(查看项目视图){ 超级(项目视图); mView=项目视图; adTitle=mView.findviewbyd(R.id.title); adLocation=mView.findviewbyd(R.id.text\u view\u key\u 4); adPrice=mView.findviewbyd(R.id.price\u text\u view); coverImage=mView.findviewbyd(R.id.company\u image\u view); coverImage.layout(0,0,0,0); } } @非空 @凌驾 public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup父级,int-viewType){ LayoutInflater LayoutInflater=LayoutInflater.from(parent.getContext()); 视图=布局更平坦。充气(R.layout.advertication\u list\u item,parent,false); 返回新的CustomViewHolder(视图); } @凌驾 public void onBindViewHolder(@NonNull CustomViewHolder,int位置){ holder.adTitle.setText(dataList.get(position.getTitle()); holder.adLocation.setText(dataList.get(position.getParish()); if(dataList.get(position).getPrice().length()=0){ holder.adPrice.setText(R.string.agreement); }否则{ holder.adPrice.setText(dataList.get(position.getPrice()+“توان”); } GlideApp.with(上下文) .load(dataList.get(position.getPicture()) .错误(R.drawable.default_pic) .diskCacheStrategy(diskCacheStrategy.ALL) .override(dataList.get(position).getPictureWidth(),dataList.get(position).GetPictureHight()) .占位符(R.drawable.default_pic) .centerCrop() .插入(支架、封面图像); } @凌驾 public int getItemCount(){ 返回dataList.size(); } }

为了让我的recyclerview永无止境,我使用这个类:

abstract class EndlessRecyclerViewScrollListener extends RecyclerView.OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 1;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private final int startingPageIndex = 0;


private RecyclerView.LayoutManager mLayoutManager;

public EndlessRecyclerViewScrollListener(LinearLayoutManager layoutManager) {
    this.mLayoutManager = layoutManager;
}

public EndlessRecyclerViewScrollListener(GridLayoutManager layoutManager) {
    this.mLayoutManager = layoutManager;
    visibleThreshold = visibleThreshold * layoutManager.getSpanCount();
}

public EndlessRecyclerViewScrollListener(StaggeredGridLayoutManager layoutManager) {
    this.mLayoutManager = layoutManager;
    visibleThreshold = visibleThreshold * layoutManager.getSpanCount();
}

private int getLastVisibleItem(int[] lastVisibleItemPositions) {
    int maxSize = 0;
    for (int i = 0; i < lastVisibleItemPositions.length; i++) {
        if (i == 0) {
            maxSize = lastVisibleItemPositions[i];
        } else if (lastVisibleItemPositions[i] > maxSize) {
            maxSize = lastVisibleItemPositions[i];
        }
    }
    return maxSize;
}

// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
@Override
public void onScrolled(RecyclerView view, int dx, int dy) {
    int lastVisibleItemPosition = 0;

    int totalItemCount = mLayoutManager.getItemCount();

    if (mLayoutManager instanceof StaggeredGridLayoutManager) {

        int[] lastVisibleItemPositions = ((StaggeredGridLayoutManager) mLayoutManager).findLastVisibleItemPositions(null);
        // get maximum element within the list
        lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions);
    } else if (mLayoutManager instanceof GridLayoutManager) {

        lastVisibleItemPosition = ((GridLayoutManager) mLayoutManager).findLastVisibleItemPosition();
    } else if (mLayoutManager instanceof LinearLayoutManager) {

        lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
    }

    // If the total item count is zero and the previous isn't, assume the
    // list is invalidated and should be reset back to initial state
    if (totalItemCount < previousTotalItemCount) {

        this.currentPage = this.startingPageIndex;
        this.previousTotalItemCount = totalItemCount;
        if (totalItemCount == 0) {

            this.loading = true;
        }
    }
    // If it’s still loading, we check to see if the dataset count has
    // changed, if so we conclude it has finished loading and update the current page
    // number and total item count.
    if (loading && (totalItemCount > previousTotalItemCount)) {

        loading = false;
        previousTotalItemCount = totalItemCount;
    }

    // If it isn’t currently loading, we check to see if we have breached
    // the visibleThreshold and need to reload more data.
    // If we do need to reload some more data, we execute onLoadMore to fetch the data.
    // threshold should reflect how many total columns there are too
    if (!loading && (lastVisibleItemPosition + visibleThreshold) > totalItemCount && dy > 0) {

        currentPage++;
        onLoadMore(currentPage, totalItemCount, view);
        loading = true;
    }
    if (!loading && (lastVisibleItemPosition + visibleThreshold) > totalItemCount) {
        currentPage++;
        onLoadMore(currentPage, totalItemCount, view);
        loading = true;
    }
}

// Call this method whenever performing new searches
public void resetState() {
    this.currentPage = this.startingPageIndex;
    this.previousTotalItemCount = 0;
    this.loading = true;
}

// Defines the process for actually loading more data based on page
protected abstract void onLoadMore(int page, int totalItemsCount, RecyclerView view);
}
抽象类endlessRecycleWebScrollListener扩展了RecycleView.OnScrollListener{
//低于当前滚动位置的最小项目数
//在加载更多之前。
私有int visibleThreshold=1;
//已加载数据的当前偏移索引
private int currentPage=0;
//上次加载后数据集中的项目总数
private int previousTotalItemCount=0;
//如果仍在等待加载最后一组数据,则为True。
私有布尔加载=真;
//设置起始页索引
私有最终整型起始页面索引=0;
private RecyclerView.LayoutManager MLLayoutManager;
public endlessRecycleViewScrollListener(LinearLayoutManager布局管理器){
this.mLayoutManager=layoutManager;
}
public endlessRecycleViewScrollListener(GridLayoutManager布局管理器){
this.mLayoutManager=layoutManager;
VisibleThrreshold=VisibleThrreshold*layoutManager.getSpanCount();
}
public EndlessRecycleViewScrollListener(交错边缘布局管理器布局管理器){
this.mLayoutManager=layoutManager;
VisibleThrreshold=VisibleThrreshold*layoutManager.getSpanCount();
}
私有int getLastVisibleItem(int[]lastVisibleItemPositions){
int maxSize=0;
对于(int i=0;imaxSize){
maxSize=lastVisibleItemPositions[i];
}
}
返回最大大小;
}
//在滚动过程中,这种情况在一秒钟内会发生很多次,因此请小心放置在此处的代码。
//我们得到了一些有用的参数,以帮助我们确定是否需要加载更多数据,
//但首先我们检查是否在等待前一次加载完成。
@凌驾
已克隆的公共无效(RecyclerView视图、int dx、int dy){
int lastVisibleItemPosition=0;
int totalItemCount=mLayoutManager.getItemCount();
if(交错边缘布局管理器的mLayoutManager实例){
int[]lastVisibleItemPositions=((StaggedGridLayoutManager)mLayoutManager)。findLastVisibleItemPositions(null);
//获取列表中的最大元素
lastVisibleItemPosition=getLastVisibleItem(lastVisibleItemPositions);
}else if(网格布局管理器的mLayoutManager实例){
lastVisibleItemPosition=((GridLayoutManager)mLayoutManager).findLastVisibleItemPosition();
}else if(线性布局管理器的mLayoutManager实例){
lastVisibleItemPosition=((LinearLayoutManager)mLayoutManager)。findLastVisibleItemPosition();
}
//如果项目总数为零,而前一个不是,则假定
//列表无效,应重置回初始状态
if(totalItemCountpreviousTotalItemCount)){
加载=假;
previousTotalItemCount=totalItemCount;
}
//如果当前未加载,我们将检查是否已违反
//VisibleSThreshold已关闭,需要重新加载更多数据。
//如果确实需要重新加载一些数据,则执行onLoadMore来获取数据。
//阈值应反映出有多少个总列
如果(!loading&&(lastVisibleItemPosition+visibleThreshold
/*Method to generate List of data using RecyclerView with custom adapter*/
private void generateDataList(final List<Ad> photoList) {

    StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(staggeredGridLayoutManager);

    adapter = new CustomAdapter(getActivity(), photoList);
    recyclerView.setAdapter(adapter);
    EndlessRecyclerViewScrollListener scrollListener;
    scrollListener = new EndlessRecyclerViewScrollListener(staggeredGridLayoutManager) {
        @Override
        public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
            // Triggered only when new data needs to be appended to the list
            // Add whatever code is needed to append new items to the bottom of the list
            loadNextDataFromApi(page);
        }
    };
    recyclerView.addOnScrollListener(scrollListener);

}
private void loadNextDataFromApi(int offset) {
    loadingSnackBar.show();

    Call<List<Ad>> call = service.getAllPhotosprime(offset + 1);
    Callback<List<Ad>> callback = new Callback<List<Ad>>() {
        @Override
        public void onResponse(@NonNull Call<List<Ad>> call, @NonNull Response<List<Ad>> response) {

            if (response.code() == 200) {

                loadingSnackBar.dismiss();
                adList.addAll(response.body());

                adapter.notifyItemInserted(adList.size() - 1);
                adapter.notifyDataSetChanged();

            } else {

                call.clone().enqueue(this);

            }
        }

        @Override
        public void onFailure(@NonNull Call<List<Ad>> call, @NonNull Throwable t) {
            loadingSnackBar.dismiss();
            call.clone().enqueue(this);
            Toast.makeText(getActivity(), "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
        }
    };
    call.enqueue(callback);
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorback"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycleViewVideo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/prograssbar" />

    <ProgressBar
        android:id="@+id/prograssbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/adView"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:visibility="visible" />

    <LinearLayout
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" />
</RelativeLayout>