从RecyclerView中删除所有项目

use*_*977 41 android adapter android-recyclerview

我试图从我RecyclerViewonRestart方法中删除所有元素,因此项目不会被加载两次:

@Override
protected void onRestart() {
    super.onRestart();

    // first clear the recycler view so items are not populated twice
    for (int i = 0; i < recyclerAdapter.getSize(); i++) {
        recyclerAdapter.delete(i);
    }

    // then reload the data
    PostCall doPostCall = new PostCall(); // my AsyncTask... 
    doPostCall.execute();
}
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,delete我在其中创建的方法adapter无法正常运行:

在RecyclerAdapter.java中:

public void delete(int position){
    myList.remove(position);
    notifyItemRemoved(position);
}

public int getSize(){
    return myList.size();
}
Run Code Online (Sandbox Code Playgroud)

我认为列表中的每个其他项都会被删除而不是整个列表.

有一个listview它很容易,我只是打电话adapter.clear().

有人可以帮我修改一下代码吗?

我想我应该用,notifyItemRangeRemoved(...,...);但我不确定如何.TIA

Boj*_*man 61

避免在for循环中删除项目并在每次迭代中调用notifyDataSetChanged.相反,只需在列表中调用clear方法myList.clear();,然后通知适配器

public void clearData() {
    myList.clear(); // clear list
    mAdapter.notifyDataSetChanged(); // let your adapter know about the changes and reload view.
}
Run Code Online (Sandbox Code Playgroud)

  • 有时我在清除时会出现异常并在recyclerview中添加新项目.java.lang.IndexOutOfBoundsException:检测到不一致.视图持有者适配器位置ViewHolder无效 (2认同)

Jar*_*ows 59

这对我很有用:

public void clear() {
    int size = data.size();
    if (size > 0) {
        for (int i = 0; i < size; i++) {
            data.remove(0);
        }

        notifyItemRangeRemoved(0, size);
    }
}
Run Code Online (Sandbox Code Playgroud)

资料来源: https ://github.com/mikepenz/LollipopShowcase/blob/master/app/src/main/java/com/mikepenz/lollipopshowcase/adapter/ApplicationAdapter.java

要么:

public void clear() {
    int size = data.size();
    data.clear();
    notifyItemRangeRemoved(0, size);
}
Run Code Online (Sandbox Code Playgroud)

为了你:

@Override
protected void onRestart() {
    super.onRestart();

    // first clear the recycler view so items are not populated twice
    recyclerAdapter.clear();

    // then reload the data
    PostCall doPostCall = new PostCall(); // my AsyncTask... 
    doPostCall.execute();
}
Run Code Online (Sandbox Code Playgroud)

  • 在`clearData()`中,为什么不简单地做:`myList.clear()`? (14认同)
  • @kip2在`RecyclerView`中没有`clear()`方法 (4认同)

Акс*_*мир 16

setAdapter(null);
Run Code Online (Sandbox Code Playgroud)

如果RecycleView具有不同的视图类型,则很有用


Sai*_*mad 15

recyclerView.removeAllViewsInLayout();
Run Code Online (Sandbox Code Playgroud)

上面的代码可以帮助您从布局中删除所有视图.

为了你:

@Override
protected void onRestart() {
    super.onRestart();

    recyclerView.removeAllViewsInLayout(); //removes all the views

    //then reload the data
    PostCall doPostCall = new PostCall(); //my AsyncTask... 
    doPostCall.execute();
}
Run Code Online (Sandbox Code Playgroud)