在RecyclerView上插入新项目

时间:2017-01-27 13:03:42

标签: android android-recyclerview

我有一个REST服务,对我的请求进行分页...我需要在我的recyclerview 20上插入itens并在加载之前保留20个itens。

这是我的要求......

VeiculoRequestHelper.veiculosPaginatedRequest(Request.Method.GET, url, null, new Response.Listener<VeiculoPaginated>() {
        @Override
        public void onResponse(VeiculoPaginated response) {
            AnalyticsTracker.getInstance().sendEvent(AnalyticsEnum.Category.MY_VEHICLE, AnalyticsEnum.Action.CLICK, AnalyticsEnum.Label.SUCCESS);

            isLast = response.isLast();

            ArrayList<Veiculo> veiculoArrayList = new ArrayList<>();
            veiculoArrayList.addAll(response.getContent());

            veiculos = veiculoArrayList;

            mAdapter.addItem(veiculos);

            mRecyclerView.setAdapter(mAdapter);

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            AnalyticsTracker.getInstance().sendEvent(AnalyticsEnum.Category.MY_VEHICLE, AnalyticsEnum.Action.CLICK, AnalyticsEnum.Label.ERROR);

            Toast.makeText(getActivity(), "Erro ao realizar listagem de veículos.", Toast.LENGTH_LONG).show();
        }
    });

这是我添加新的itens的适配器方法......

    public void addItem(ArrayList<Veiculo> veiculosArray) {
    if (veiculos != null) {
        veiculos.clear();
        veiculos.addAll(veiculosArray);
        notifyItemInserted(veiculos.size() - 1);
    } else {
        veiculos = veiculosArray;
    }
    notifyDataSetChanged();
}

我做错了什么?插入itens但不保留旧的itens ...请帮助!

2 个答案:

答案 0 :(得分:1)

旧数据将在addItem(ArrayList<Veiculo> veiculosArray)中清除:

if (veiculos != null) {
  veiculos.clear(); // here they will be cleared
  veiculos.addAll(veiculosArray);
  notifyItemInserted(veiculos.size() - 1);
}

删除此行以保留旧项目。

答案 1 :(得分:0)

你的onResponse中的

 ArrayList<Veiculo> veiculoArrayList = new ArrayList<>();
            veiculoArrayList.addAll(response.getContent());

            veiculos = veiculoArrayList;

            mAdapter.addItem(veiculos);

            mRecyclerView.setAdapter(mAdapter);

看看发生了什么,veiculoArrayList被分配到veiculos表示现在有新的20个项目。 将veiculos传递给mAdapter.addItem(veiculos); 并在您的addItem方法

veiculos.clear();
veiculos.addAll(veiculosArray);

表示veiculos中的内容将清除,新的列表veiculosArray将被添加到其中(表示新的20个项目)。您不需要清除,添加新项目列表和notifyDatasetChanged()。 要专注于最后一项,你只需要设置recyclerView.smoothScrollToPosition(position); 显然,在将新项目添加到其中之前,位置将是veiculos.size()。

notifyItemRangeInserted(lastListSize, newList.size());