从 RecyclerView 中删除所有项目 [英] Remove all items from RecyclerView

查看:24
本文介绍了从 RecyclerView 中删除所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的 onRestart 方法中从我的 RecyclerView 中删除所有元素,以便项目不会被加载两次:

I am trying to remove all the elements from my RecyclerView in my onRestart method so the items don't get loaded twice:

@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();
}

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

But for some reason the delete method I created in the adapter is not functioning properly:

在 RecyclerAdapter.java 中:

in RecyclerAdapter.java:

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

public int getSize(){
    return myList.size();
}

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

I think every other item in my list gets deleted instead of the entire list.

使用 listview 非常简单,我只需调用 adapter.clear().

With a listview it was so easy and I simply called adapter.clear().

有人可以帮我修复代码吗?

Can someone please help me fix up the code?

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

I think I should be using notifyItemRangeRemoved(...,...); but I am not sure how. TIA

推荐答案

这对我很有用:

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

        notifyItemRangeRemoved(0, size);
    }
}

来源: 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);
}

给你:

@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();
}

这篇关于从 RecyclerView 中删除所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆