分页无法在Android上正常运行。一次显示所有项目

时间:2019-03-09 06:53:21

标签: android performance

我有30个项目的recyclerview。当我尝试滚动时,分页不起作用。它显示所有项目而不是刷新。下面是我的代码。

public class InstitutesWithSearchActivity extends AppCompatActivity {
PaginationAdapter adapter;
private static final int PAGE_START = 1;
private boolean isLoading, isLastPage = false;
private int TOTAL_PAGES = 2;
int itemCount = 0;
private int currentPage = PAGE_START;
ApiInterface apiInterface;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    adapter = new PaginationAdapter(this);
    layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(adapter);

    recyclerView.addOnScrollListener(new PaginationScrollListener(layoutManager) {
        @Override
        protected void loadMoreItems() {
            isLoading = true;
            currentPage += 1;

            //mocking network delay for api
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadNextPage();
                }
            },2000);
        }

        @Override
        public int getTotalPageCount() {
            return TOTAL_PAGES;
        }

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

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

    //init service and load data
    apiInterface = ApiClient.getClient().create(ApiInterface.class);
     loadFirstPage();
}
private void loadNextPage() {
    Call<InstituteResponseModel> call = apiInterface.masterInstitutes();
    call.enqueue(new Callback<InstituteResponseModel>() {
        @Override
        public void onResponse(Call<InstituteResponseModel> call, Response<InstituteResponseModel> response) {
            adapter.removeLoadingFooter();
            isLoading = false;
            ArrayList<InstituteModel> results = fetchResults(response);
            adapter.addAll(results);
            if (currentPage != PAGE_START) adapter.removeLoadingFooter();
            adapter.addAll(results);

            if (currentPage < TOTAL_PAGES) adapter.addLoadingFooter();
            else isLastPage = true;
            isLoading = false;
        }

        @Override
        public void onFailure(Call<InstituteResponseModel> call, Throwable t) {
            t.printStackTrace();
        }
    });
}

private void loadFirstPage() {
    Log.e(TAG,"loadFirstPage");

    Call<InstituteResponseModel> call = apiInterface.masterInstitutes();
    call.enqueue(new Callback<InstituteResponseModel>() {
        @Override
        public void onResponse(Call<InstituteResponseModel> call, Response<InstituteResponseModel> response) {
            ArrayList<InstituteModel> results = fetchResults(response);
            progressBar.setVisibility(View.GONE);
            adapter.addAll(results);

            if (currentPage <= TOTAL_PAGES) adapter.addLoadingFooter();
            else isLastPage = true;

        }

        @Override
        public void onFailure(Call<InstituteResponseModel> call, Throwable t) {
            t.printStackTrace();
        }
    });
}

private ArrayList<InstituteModel> fetchResults(Response<InstituteResponseModel> response) {
    InstituteResponseModel responseModel = response.body();
    return  responseModel.getData();
}

}

我不知道我这边有什么错误。我是这个分页概念的新手。我正在获取使用forloop显示数据的示例代码。我正在使用API​​在Recyclerview中显示数据。

公共类PaginationAdapter扩展了RecyclerView.Adapter {

private static final int ITEM = 0;
private static final int LOADING = 1;
boolean isLoadingAdded = false;

private ArrayList<InstituteModel> modelArrayList;
Context context;

public PaginationAdapter(Context context) {
    this.context = context;
    modelArrayList = new ArrayList<>();
}

public ArrayList<InstituteModel> getInstitutes() {
    return modelArrayList;
}

public void setInstitutes(ArrayList<InstituteModel> modelArrayList) {
    this.modelArrayList = modelArrayList;
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    RecyclerView.ViewHolder viewHolder = null;
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());

    switch (viewType){
        case ITEM:
            viewHolder = getViewHolder(parent, inflater);
            break;
        case LOADING:
            View v2 = inflater.inflate(R.layout.item_progress, parent, false);
            viewHolder = new LoadingVH(v2);
            break;
    }
    return viewHolder;
}

private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater){
    RecyclerView.ViewHolder viewHolder;
    View v1 = inflater.inflate(R.layout.institute_row_layout, parent, false);
    viewHolder = new InstituteHolder(v1);
    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int parent) {
    InstituteModel model = modelArrayList.get(parent);
    switch (getItemViewType(parent)){
        case ITEM:
            final InstituteHolder instituteHolder = (InstituteHolder) holder;
            instituteHolder.instName.setText(model.getInstituteName());
            Glide.with(context)
                    .load(model.getImageURL())
                    .listener(new RequestListener<String, GlideDrawable>() {
                        @Override
                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                            instituteHolder.progressBar.setVisibility(GONE);
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                            instituteHolder.progressBar.setVisibility(GONE);
                            return false;
                        }
                    })
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .crossFade()
                    .into(instituteHolder.instImg);
            break;
        case LOADING:
            break;
    }

}

@Override
public int getItemCount() {
    return modelArrayList == null ? 0 : modelArrayList.size();
}

@Override
public int getItemViewType(int position) {
    return (position == modelArrayList.size()-1 && isLoadingAdded) ? LOADING : ITEM;
}

public void add(InstituteModel m){
    modelArrayList.add(m);
    notifyItemInserted(modelArrayList.size()-1);
}

public void addAll(ArrayList<InstituteModel> modelsList){
    for (InstituteModel model : modelsList){
        add(model);
    }
}

public void remove(InstituteModel model){
    int position = modelArrayList.indexOf(model);
    if (position > -1){
        modelArrayList.remove(position);
        notifyItemRemoved(position);
    }
}

public void clear(){
    isLoadingAdded = false;
    while (getItemCount()>0){
        remove(getItem(0));
    }
}

public boolean isEmpty(){
    return  getItemCount() == 0;
}

public void addLoadingFooter(){
    isLoadingAdded = true;
    add(new InstituteModel());
}


public void removeLoadingFooter(){
    isLoadingAdded = false;
    int position = modelArrayList.size() -1;
    InstituteModel result = getItem(position);
    if (result != null){
        modelArrayList.remove(position);
        notifyItemRemoved(position);
    }
}

public InstituteModel getItem(int position){return  modelArrayList.get(position);}

protected class InstituteHolder extends RecyclerView.ViewHolder {
    TextView instName;
    ImageView instImg;
    TextView cityName, areaName;
    RelativeLayout cardView;
    ProgressBar progressBar;

    public InstituteHolder(@NonNull View itemView) {
        super(itemView);
        instImg = itemView.findViewById(R.id.course_image);
        instName = itemView.findViewById(R.id.course_name);
        areaName = itemView.findViewById(R.id.course_area);
        cityName = itemView.findViewById(R.id.course_city);
        progressBar = itemView.findViewById(R.id.imgProgress);
        cardView = itemView.findViewById(R.id.cardView);
    }
}

protected class LoadingVH extends RecyclerView.ViewHolder {
    public LoadingVH(@NonNull View itemView) {
        super(itemView);
    }
}

}

0 个答案:

没有答案