分页的Recyclerview的页面增量索引

时间:2018-06-21 05:30:35

标签: android android-recyclerview onscrolllistener

我已经在我的应用程序中实现了分页,但是在增加页面索引方面遇到了麻烦。我正在从unsplash api获取数据,并形成了如下所示的请求网址:

private String url = Constants.SEARCH_URL + "top30&page="+ PAGE_INDEX;

这是下面使用的网址:

https://api.unsplash.com/search/photos?client_id=api_key&order_by=latest&query=top30&page=1

在我的片段中,我有一个常量private static int PAGE_INDEX = 1;,它跟踪当前页面并用于获取下一页直到页面限制。

第一个请求运行正常,当滚动到最后一个项目时,将提取更多项目。但是,这些项与首页索引中的项相同,并且在记录了网址后,我得到的内容与第一个请求中的相同,如下所示:

https://api.unsplash.com/search/photos?client_id=api_key&order_by=latest&query=top30&page=1

我已经将滚动侦听器附加到了recyclerview中,并递增了PAGE_INDEX,但没有获得url中的下一页,但是在log cat中它显示页面索引为2。这是附加的侦听器:

top30RV.addOnScrollListener(new PaginationScrollListener(llm) {
        @Override
        protected void loadMoreItems() {
            isLoading = true;
            PAGE_INDEX = PAGE_INDEX + 1;
            Log.d(TAG, "PIn:\t" + PAGE_INDEX);

            loadNextPage();

        }

        @Override
        protected int getTotalPageCount() {
            return PAGE_COUNT;
        }

        @Override
        public boolean isLoading() {
            return isLoading;
        }

        @Override
        public boolean isLastPage() {
            return isLastPage;
        }

    });

和我的PaginationScrollListener类代码:

public abstract class PaginationScrollListener extends RecyclerView.OnScrollListener {

LinearLayoutManager llm;

public PaginationScrollListener(LinearLayoutManager llm) {
    this.llm = llm;
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);

    int visisbleItemCount = recyclerView.getChildCount();
    int totalItemCount = llm.getItemCount();
    int firstVisibleItemPosn = llm.findFirstVisibleItemPosition();

    if (!isLoading() && !isLastPage()){
        if ((visisbleItemCount + firstVisibleItemPosn) >= totalItemCount && firstVisibleItemPosn > 0){
            loadMoreItems();
        }
    }

}

protected abstract void loadMoreItems();

protected abstract int getTotalPageCount();

public abstract boolean isLoading();

public abstract boolean isLastPage();

}

在我的适配器中,我已经调用了addLoadingFooter的方法,该方法可以工作,但是进度条没有被取消,removeLoadingFooter被调用但由于页面索引小于页面而无法工作限制。

public class Top30Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private static final String TAG = Top30Adapter.class.getSimpleName();

private final Context context;
private List<UnsplashImages> itemsList;

private UnsplashImages unsplashImages;

private static final int ITEMS = 0;
private static final int PROGRESS = 1;

private boolean isLoadingAdded = false;
private boolean retryPageLoad = false;

private String errorMsg;

private PaginationAdapterCallback mCallback;

public Top30Adapter(Context context, List<UnsplashImages> itemsList) {
    this.context = context;
    this.itemsList = itemsList;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    switch (viewType){
        case ITEMS:
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.wallpaper_items_layout, parent, false);
            return new WallpaperItemViewHolder(view);
        case PROGRESS:
            View pv = LayoutInflater.from(parent.getContext()).inflate(R.layout.progress_items_layout, parent, false);
            return new LoadingViewHolder(pv);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewholder, final int position) {
    switch (getItemViewType(position)){
        case ITEMS:
            WallpaperItemViewHolder wallpaperItemViewHolder = (WallpaperItemViewHolder) viewholder;
            unsplashImages = (UnsplashImages) itemsList.get(position);
            Picasso.with(context)
                    .load(unsplashImages.getRegularImg())
                    .placeholder(R.drawable.drawer_header_trimmed)
                    .into(wallpaperItemViewHolder.wallpaperItemImg);

            wallpaperItemViewHolder.favoriteWP_IV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Favorites favorites = new Favorites();
                    favorites.setFavoritesId(UUID.randomUUID().toString());
                    favorites.setLargeImgURL(unsplashImages.getRegularImg());
                    favorites.setPreviewImgURL(unsplashImages.getRegularImg());
                    favorites.save();
                    Toast.makeText(context, "Added to Favorites", Toast.LENGTH_SHORT).show();

                }
            });

            wallpaperItemViewHolder.setWallPaper_TV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final WallpaperManager wpm = WallpaperManager.getInstance(context);

                    Picasso.with(context)
                            .load(((UnsplashImages) itemsList.get(position)).getRegularImg())
                            .into(new Target() {
                                @Override
                                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                                    try {
                                        wpm.setBitmap(bitmap);
                                        Toast.makeText(context, "Your New Wallpaper Has Been Set", Toast.LENGTH_SHORT).show();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onBitmapFailed(Drawable errorDrawable) {
                                    Log.d(TAG, "Bitmap Load Failed");
                                    Toast.makeText(context, "Could Not Set Wallpaper...Choose Another", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onPrepareLoad(Drawable placeHolderDrawable) {
                                    Log.d(TAG, "Prep to Load Bitmap");
                                }
                            });

                }
            });
            break;
        case PROGRESS:
            LoadingViewHolder loadingViewHolder = (LoadingViewHolder) viewholder;
            if (retryPageLoad){
                loadingViewHolder.mErrorLayout.setVisibility(View.VISIBLE);
                loadingViewHolder.mProgressBar.setVisibility(View.GONE);

                loadingViewHolder.mErrorTxt.setText(errorMsg != null
                        ? errorMsg
                        : context.getString(R.string.error_msg_unknown));

            } else {
                loadingViewHolder.mErrorLayout.setVisibility(View.GONE);
                loadingViewHolder.mProgressBar.setVisibility(View.VISIBLE);
            }
            break;
    }
}

@Override
public int getItemCount() {
    if (itemsList == null) {
        return 0;
    }
    return itemsList.size();
}

@Override
public int getItemViewType(int position) {
    return (position == itemsList.size() - 1 && isLoadingAdded) ? PROGRESS : ITEMS;
}

public void addImage(UnsplashImages images){
    itemsList.add(images);
    notifyItemInserted(itemsList.size() - 1);
}

public void addAllImages(List<UnsplashImages> list){
    for (UnsplashImages images : list){
        addImage(images);
    }
}

public void addLoadingFooter() {
    isLoadingAdded = true;
    addImage(new UnsplashImages());
}

public void removeLoadingFooter(){
    isLoadingAdded = false;

    int position = itemsList.size() - 1;
    UnsplashImages unsplashImages = getItem(position);

    if (unsplashImages != null){
        itemsList.remove(unsplashImages);
        notifyItemRemoved(position);
    }

}

private UnsplashImages getItem(int position) {
    return itemsList.get(position);
}

public void showRetry(boolean show, @Nullable String errorMsg){
    retryPageLoad = true;
    notifyItemChanged(itemsList.size() - 1);
    if (errorMsg != null){this.errorMsg = errorMsg; } else { errorMsg = "Can't Fetch Wallpapers Now..."; }
}

}

完整的片段代码:

public class Top30Fragment extends Fragment {

private static final String TAG = Top30Fragment.class.getSimpleName();

private RecyclerView top30RV;

private List<UnsplashImages> itemsList = new ArrayList<>();
private Top30Adapter adapter;

private int PAGE_COUNT;
private static int PAGE_INDEX = 1;
private static int PER_PAGE = 20;
private static int CURRENT_PAGE = PAGE_INDEX;

private boolean isLoading = false;
private boolean isLastPage = false;

private String url = Constants.SEARCH_URL + "top30&page="+ PAGE_INDEX;

public Top30Fragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View vtop = inflater.inflate(R.layout.fragment_top30, container, false);

    top30RV = vtop.findViewById(R.id.top30RV);
    top30RV.setHasFixedSize(true);

    LinearLayoutManager llm = new LinearLayoutManager(getActivity());

    top30RV.setLayoutManager(llm);

    if (Utils.isNetwork(getActivity())){
        fetchWallpapers();
    } else {
        Snackbar.make(getActivity().findViewById(android.R.id.content), "Check Connection", Snackbar.LENGTH_LONG).show();
    }

    adapter = new Top30Adapter(getActivity(), itemsList);
    top30RV.setAdapter(adapter);

    top30RV.addOnScrollListener(new PaginationScrollListener(llm) {
        @Override
        protected void loadMoreItems() {
            isLoading = true;
            PAGE_INDEX = PAGE_INDEX + 1;
            Log.d(TAG, "PIn:\t" + PAGE_INDEX);

            loadNextPage();

        }

        @Override
        protected int getTotalPageCount() {
            return PAGE_COUNT;
        }

        @Override
        public boolean isLoading() {
            return isLoading;
        }

        @Override
        public boolean isLastPage() {
            return isLastPage;
        }

    });

    adapter.notifyDataSetChanged();

    return vtop;
}

private void loadNextPage() {
    int newIndex = PAGE_INDEX +=1;
    Log.d(TAG, "Next Page:\t" + newIndex);
    Log.d(TAG, "Next Page Index:\t" + newIndex);
    Log.d(TAG, "Next Page URL:\t" + url);
    AndroidNetworking.get(url)
            .setTag("Load Next Top30")
            .setPriority(Priority.HIGH)
            .build()
            .getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "Next Page Response:\t" + response.toString());
                    if (response != null){

                        isLoading = false;
                        adapter.removeLoadingFooter();

                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());

                            JSONArray results = jsonObject.getJSONArray("results");

                            for (int p = 0; p < results.length(); p++){
                                JSONObject items = results.getJSONObject(p);

                                UnsplashImages images = new UnsplashImages();
                                images.setImageId(items.getString("id"));

                                JSONObject urls = items.getJSONObject("urls");

                                images.setRawImg(urls.getString("raw"));
                                images.setFullImg(urls.getString("full"));
                                images.setRegularImg(urls.getString("regular"));
                                images.setSmallImg(urls.getString("small"));
                                images.setThumbImg(urls.getString("thumb"));

                                itemsList.add(images);
                                adapter.notifyDataSetChanged();

                                Log.d(TAG, "New List Size:\t" + itemsList.size());

                                if (CURRENT_PAGE != PAGE_COUNT){
                                    adapter.addLoadingFooter();
                                } else {
                                    isLastPage = true;
                                }

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(ANError anError) {

                }
            });
}

private void fetchWallpapers() {
//        String url = Constants.SEARCH_URL + "top30&page="+ PAGE_INDEX + "per_page=" + PER_PAGE;
    Log.d(TAG, "Top30 Unsplash URL:\t" + url);

    AndroidNetworking.get(url)
            .setPriority(Priority.HIGH)
            .setTag("Get Seasons Wallpapers")
            .build()
            .getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "Un-Response:\t" + response.toString());
                    if (response != null){
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());

                            PAGE_COUNT = jsonObject.getInt("total_pages");
                            Log.d(TAG, "Page Count:\t" + PAGE_COUNT);

                            JSONArray results = jsonObject.getJSONArray("results");

                            for (int p = 0; p < results.length(); p++){
                                JSONObject items = results.getJSONObject(p);

                                UnsplashImages images = new UnsplashImages();
                                images.setImageId(items.getString("id"));

                                JSONObject urls = items.getJSONObject("urls");

                                images.setRawImg(urls.getString("raw"));
                                images.setFullImg(urls.getString("full"));
                                images.setRegularImg(urls.getString("regular"));
                                images.setSmallImg(urls.getString("small"));
                                images.setThumbImg(urls.getString("thumb"));

                                itemsList.add(images);
                                adapter.notifyDataSetChanged();

                                Log.d(TAG, "List Size:\t" + itemsList.size());

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(ANError anError) {

                }
            });
}

还有另一种方法来构造请求url以增加页面索引吗?谢谢。

0 个答案:

没有答案