如何在不更改数据的情况下在适配器上添加或删除项目而不刷新

时间:2018-12-06 19:14:22

标签: android firebase

我有一个带有字符串数组列表的适配器。使用Firebase,我可以监听数据库上的更改,并且每次数据库更改时,我都从ArrayList中删除或添加项目,然后再次调用SetAdapter,这将刷新整个列表,而不仅仅是添加或删除单个项目。这是代码:

在片段中:

           public void onDataChange(DataSnapshot dataSnapshot) {
               //more code here
            mAdapter = new MyAdapter(myDataset);
            if (x<100)
                {
                    if (!myDataset.contains(datas.getKey().toString())){
                    myDataset.add(datas.getKey().toString());                           
                    mRecyclerView.setAdapter(mAdapter);
                }
            } else {                        
                myDataset.remove(datas.getKey().toString());
                mRecyclerView.setAdapter(mAdapter);
            }

现在,我怀疑我需要完全采用另一种方法,其中包括向Adapter文件中添加侦听器,但是我不确定。很想得到方向

1 个答案:

答案 0 :(得分:1)

因此,不必每次都设置适配器,而是可以在适配器内部创建几个方法来插入,更新或删除项,并通知组件每个单独的操作,而不必再次设置适配器。

在适配器内部,您可能会遇到类似这样的情况:

public void itemChanged(int position) {
    // do your own stuff and then notify the item changed
    notifyItemChanged(position, "somethingChanged");
}

public void everythingChanged(List<String> list) {
    mList = list;
    // Notify the whole list is different and therefore we must update everything
    notifyDataSetChanged();
}

public void addText(String text) {
    mList.add(0, text);
    // Insert an item to the list at the beginning and notify the component
    notifyItemInserted(0);
}

public void updateTextPosition(String search) {
    for (int i = 0; i < mList.size(); i++) {
        if (mList.get(i).equals(search)) {
            // move item and do you own stuff
            notifyItemMoved(replace_with_current_pos, replace_with_new_pos);
            break;
        }
    }
}

public void removeTextAtPosition(int position) {
    mList.remove(i);
    notifyItemRemoved(i);
}

有关notify事件的更多信息,请转到RecyclerView documentation

然后在“活动”中,仅保存对适配器的引用,并按如下所示调用每个方法:

mAdapter.removeTextAtPosition(1);