RecyclerView未使用notifyDatasetChanged更新,直到向上滚动

时间:2017-07-04 06:00:45

标签: android pagination android-recyclerview recycler-adapter

我在我的Recycler视图上使用gridLayoutManager并希望在其上实现分页。我的问题是,当我到达视图的底部并从服务添加数据时,我使用notifyDataSetChanged或notifyItemRangeChanged,recyclelerView不会更新,直到我向上滚动它。如果我再次设置适配器并将位置设置到前一个位置,则会出现闪烁效果,这种效果并不平滑。这是我尝试过的,但似乎没有任何工作

//adding data to my list
mNewsList.addAll((List<NewDataModel>) response.body());

// i set the adapter again
int currentPosition = 
gaggeredGridLayoutManager.findLastVisibleItemPosition();
adapter = new RecyclerViewAdapter(mNewsList, Utilities.getThin(getActivity()), (AppCompatActivity) getActivity(), mHeaderTextView.getText().toString());            
recyclerView.setAdapter(adapter);         
gaggeredGridLayoutManager.scrollToPosition(currentPosition+1);

//adding data to my list
mNewsList.addAll((List<NewDataModel>) response.body());
adapter.notifyDataSetChanged();

adapter.notifyItemRangeChanged(0,adapter.getItemCount());

1 个答案:

答案 0 :(得分:2)

为避免闪烁效应,必须在适配器设置

后使用处理程序
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {

    //do anything

    rv_products.scrollToPosition(lastPos);
  }
}, 100);

我使用以下方式实现分页

rv_products.addOnScrollListener(new RecyclerView.OnScrollListener() {

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

    visibleItemCount = rv_products.getChildCount();
    if (productListAdapter.getViewType() == 1)
      totalItemCount = mGridLayoutManager.getItemCount();
    else
      totalItemCount = mSingleLayoutManager.getItemCount();

    if (productListAdapter.getViewType() == 1)
      firstVisibleItem = mGridLayoutManager.findFirstVisibleItemPosition();
    else
      firstVisibleItem = mSingleLayoutManager.findFirstVisibleItemPosition();

    if (loading) {
      if (totalItemCount > previousTotal) {
        loading = false;
        previousTotal = totalItemCount;
      }
    }
    if (!loading && (totalItemCount - visibleItemCount)
          <= (firstVisibleItem + visibleThreshold)) {

    if (lstProducts.size() < totalCount)
      getProducts(category_id);

      loading = true;
    }
  }
});


public void getProducts(String id) {


  pDialog.setCancelable(false);
  pDialog.show();
  PreferenceSetting preferenceSetting = PreferenceSetting.getInstance(activity);
  Map<String, String> postParam = new HashMap<String, String>();
  postParam.put("category_id", id);
  postParam.put("customer_id", preferenceSetting.getCustomerId());
  postParam.put("eventName", Constants.EVENT_GET_PRODUCTS);
  postParam.put("page", (pageIndex++) + "");

  CommonUtility.setLog("getProducts", postParam.toString());
  JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
      Constants.Server_URL, new JSONObject(postParam),
          new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
              Log.e(getBaseActivity().getLocalClassName(), response.toString());
              pDialog.dismiss();
              try {
                String message = response.getString(Constants.KEY_MESSAGE);
                if (response.getString(Constants.KEY_STATUS).equals(Constants.VALUE_STATUS_SUCCESS)) {
                  Gson gson = new Gson();
                  ProductsReponse productsReponse = gson.fromJson(response.toString(), ProductsReponse.class);
                  ((MainActivity) activity).setCartListCount(productsReponse.getData().getCartItemCount());
                  lstProducts.addAll(productsReponse.getData().getProductDetail());
                  totalCount = Integer.parseInt(productsReponse.getData().getTotalItem());
                  productListAdapter.notifyDataSetChanged();
                  tv_count.setText("(" + totalCount + " items)");

                } else {
                  // CommonUtility.ShowToast(activity, message, "");
                }
              } catch (JSONException e) {
                e.printStackTrace();

              }


            }
          }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
              pDialog.dismiss();
            }
        }) {

            /**
             * Passing some request headers
             */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
              HashMap<String, String> headers = new HashMap<String, String>();
              headers.put("Content-Type", "application/json; charset=utf-8");
              return headers;
            }


        };

  // Adding request to request queue
  MyApp.getInstance().addToRequestQueue(jsonObjReq);
}