在RecyclerView中加载更多内容时遇到麻烦

时间:2019-02-07 08:50:59

标签: android android-recyclerview lazy-loading

我必须在回收者视图中显示100个数据。所以我想更多地实现负载以提高效率。当我尝试编译代码时,进度条不会消失,并且在底部留有很大的空间。它只是加载了20个数据,而不是全部。

the progress bar with big space on the bottom

next data with big space on top

这是我的适配器的代码

   class LoadingViewHolder extends RecyclerView.ViewHolder{
    public ProgressBar progressBar;
    public LoadingViewHolder(@NonNull View itemView) {
        super(itemView);
        progressBar=(ProgressBar) itemView.findViewById(R.id.loadmore);
    }
}

class herbalViewHolder extends RecyclerView.ViewHolder{
        TextView namaHerbal,khasiatHerbal;
        ImageView thumbnail;
        public herbalViewHolder(@NonNull View itemView) {
            super(itemView);
            namaHerbal = itemView.findViewById(R.id.nama_herbal);
            khasiatHerbal = itemView.findViewById(R.id.khasiat_herbal);
            thumbnail = itemView.findViewById(R.id.gambar_herbal);
        }
    }

public class herbalAdapter extends  RecyclerView.Adapter<RecyclerView.ViewHolder>{
    private final int VIEW_TYPE_ITEM=0,VIEW_TYPE_LOADING=1;
    private loadMore loadMore;
    boolean isLoading;
    private Context mCtx;
    List<herbalModel> herbalModelList;
    int visibleThreshold=5;
    int lastVisibleItem,totalItemCount;

    public herbalAdapter(RecyclerView recyclerView,Context mCtx, List<herbalModel> herbalModelList) {
        this.mCtx = mCtx;
        this.herbalModelList = herbalModelList;

        final LinearLayoutManager linearLayoutManager = (LinearLayoutManager)recyclerView.getLayoutManager();
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                totalItemCount = linearLayoutManager.getItemCount();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                if (!isLoading && totalItemCount <= (lastVisibleItem+visibleThreshold))
                {
                    if (loadMore != null)
                        loadMore.onLoadMore();
                    isLoading=true;
                }
            }
        });
    }

    @Override
    public int getItemViewType(int position) {
        return herbalModelList.get(position) == null ? VIEW_TYPE_LOADING:VIEW_TYPE_ITEM;
    }

    public void setLoadMore(loadMore loadMore) {
        this.loadMore = loadMore;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        if(i == VIEW_TYPE_ITEM)
        {
            CardView v = (CardView) LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.cardview_herbal, parent,false);
    //        View view =inflater.inflate(R.layout.cardview_herbal,null);
            return new herbalViewHolder(v);
        }
        else if(i == VIEW_TYPE_LOADING)
        {
            View view = LayoutInflater.from(mCtx).inflate(R.layout.item_loading,parent,false);
            return new LoadingViewHolder(view);
        }

        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        if (viewHolder instanceof  herbalViewHolder)
        {
            herbalModel detailherbal =herbalModelList.get(i);
            herbalViewHolder herbalViewHolder = (herbalViewHolder) viewHolder;
            herbalViewHolder.namaHerbal.setText(detailherbal.getNama());
            herbalViewHolder.khasiatHerbal.setText(detailherbal.getKhasiat());
            Glide.with(mCtx)
                    .load(detailherbal.getThumbnail())
                    .into(herbalViewHolder.thumbnail);
            final String idHerbal =detailherbal.getId();
            herbalViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(mCtx, detailHerbal.class);
                    i.putExtra("idHerbal", idHerbal);
                    mCtx.startActivity(i);

                }
            });
        }
        else if(viewHolder instanceof  LoadingViewHolder)
        {
            LoadingViewHolder loadingViewHolder = (LoadingViewHolder) viewHolder;
            loadingViewHolder.progressBar.setIndeterminate(true);
        }
    }

    @Override
    public int getItemCount() {
        return herbalModelList.size();
    }

    public void setLoaded() {
        isLoading = false;
    }

    public void filterlist (ArrayList<herbalModel> filteredList)
    {
        herbalModelList =filteredList;
        notifyDataSetChanged();
    }
}

这是显示recyclerview的主要活动

    private void get10Data() {

        String url ="https://jsonplaceholder.typicode.com/photos";
        JsonArrayRequest request = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArray) {
                        Log.d(TAG,"Onresponse"+jsonArray.toString());
                        for(int i = 0; i < 10; i++) {
                            try {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                Log.d(TAG,"jsonobject"+jsonObject);
                                herbalModels.add(
                                        new herbalModel(
                                                jsonObject.getString("title"),
                                                "Khasiat",
                                                jsonObject.getString("albumId"),
                                                jsonObject.getString("id"),
                                                jsonObject.getString("thumbnailUrl")
                                        )
                                );
                            }
                            catch(JSONException e) {

                            }
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d(TAG,"Onerror"+volleyError.toString());
                    }
                });
        MySingleton.getInstance(getActivity()).addToRequestQueue(request);
    }
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_herbal, container, false);
        herbalModels = new ArrayList<>();

        RequestQueue queue = MySingleton.getInstance(this.getActivity().getApplicationContext()).getRequestQueue();
        get10Data();

        sortData(rootView);
        StartRecyclerView(rootView);

        return rootView ;

    }

    private void StartRecyclerView(View rootView) {
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));


        adapter = new herbalAdapter(recyclerView,getActivity(),herbalModels);
        recyclerView.setAdapter(adapter);

        //set loaded more event
        adapter.setLoadMore(new loadMore() {
            @Override
            public void onLoadMore() {
                if (herbalModels.size() <= 20)
                {
                    herbalModels.add(null);
                    adapter.notifyItemInserted(herbalModels.size()-1);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            herbalModels.remove(herbalModels.size()-1);
                            adapter.notifyItemRemoved(herbalModels.size());
                            final int index = herbalModels.size();
                            final int end = index+10;
                            String url ="https://jsonplaceholder.typicode.com/photos";
                            JsonArrayRequest request = new JsonArrayRequest(url,
                                    new Response.Listener<JSONArray>() {
                                        @Override
                                        public void onResponse(JSONArray jsonArray) {
                                            Log.d(TAG,"Onresponse"+jsonArray.toString());
                                            for(int i = index; i < end; i++) {
                                                try {
                                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                                    Log.d(TAG,"jsonobject"+jsonObject);
                                                    herbalModels.add(
                                                            new herbalModel(
                                                                    jsonObject.getString("title"),
                                                                    "Khasiat",
                                                                    jsonObject.getString("albumId"),
                                                                    jsonObject.getString("id"),
                                                                    jsonObject.getString("thumbnailUrl")
                                                            )
                                                    );
                                                }
                                                catch(JSONException e) {

                                                }
                                            }

                                        }
                                    },
                                    new Response.ErrorListener() {
                                        @Override
                                        public void onErrorResponse(VolleyError volleyError) {
                                            Log.d(TAG,"Onerror"+volleyError.toString());
                                        }
                                    });
                            MySingleton.getInstance(getActivity()).addToRequestQueue(request);
                            adapter.notifyDataSetChanged();
                            adapter.setLoaded();
                        }
                    },5000);
                }
            }
        });
    }

0 个答案:

没有答案