Android - RecyclerView notifyItemRemoved无法正常工作

时间:2015-10-17 16:20:30

标签: android android-recyclerview

我在最后为progressBar添加了一个项目以便加载更多内容,当加载完成时,我在添加适配器末尾的元素之前删除了这个项目。 但该项目未被正确删除。

if (arrayAdapter != null) {
        arrayAdapter.list.add(null);
        arrayAdapter.notifyItemInserted(arrayAdapter.getItemCount() - 1);
        arrayAdapter.notifyItemRangeChanged(arrayAdapter.getItemCount(), arrayAdapter.getItemCount());
    }
    serverRequests.getQuestionsAnsweredInBackground(userID, type, startLoad, new GetQuestionCallBack() {
        @Override
        public void done(ArrayList<Question> questions) {
            if (arrayAdapter != null) {
                arrayAdapter.list.remove(arrayAdapter.getItemCount() - 1);
                arrayAdapter.notifyItemRemoved(arrayAdapter.getItemCount());
                arrayAdapter.notifyItemRangeChanged(arrayAdapter.getItemCount(), arrayAdapter.getItemCount());
            }
            if (questions != null) {
                if (arrayAdapter == null) {
                    arrayAdapter = new QuestionsAnsweredAdapter(getActivity(), R.layout.layout_questions_answered_item, questions, QuestionsAnswered.this);
                    lvQuestionsAnswered.setAdapter(arrayAdapter);
                    listLayout.setVisibility(View.VISIBLE);
                } else {
                    final int positionStart = arrayAdapter.getItemCount();
                    arrayAdapter.list.addAll(questions);
                    arrayAdapter.notifyItemRangeInserted(positionStart, questions.size());
                }
                startLoad += questions.size();
                loading = true;
            }
            progressBar.setVisibility(View.GONE);
        }
    });

enter image description here

1 个答案:

答案 0 :(得分:0)

加载新数据之前

if(!mIsloading)
{
  arrayAdapter.list.add(null);
  arrayAdapter.notifyItemInserted(arrayAdapter.list.size() - 1);
  mIsloading = true; 
}

完成提取数据后

serverRequests.getQuestionsAnsweredInBackground(userID, type, startLoad, new GetQuestionCallBack() {
        @Override
        public void done(ArrayList<Question> questions) {
           if (arrayAdapter.list.size() > 0 && arrayAdapter.list.get(arrayAdapter.list.size() - 1) == null) {
                    arrayAdapter.list.remove(arrayAdapter.list.size() - 1);
                    arrayAdapter.list.notifyItemRemoved(arrayAdapter.list.size());
                }
          mIsloading = false;   
            }