简体   繁体   English

从recyclerView上的特定位置移除物品

[英]Remove items from specific positions on recyclerView

I have a recyclerView and a List<> which contains some random position 我有一个recyclerView和一个List<> ,其中包含一些随机位置

All i want to do is remove recyclerView item from position stored in the list. 我要做的就是从列表中存储的position删除recyclerView项目。

更好的方法是从Adapter中删除对象,然后调用notifyDatasetChanged

from your activity you can loop your list of item position you want to delete 从您的活动中,您可以循环显示要删除的项目位置列表

for(int i = 0; i< listitem.size(); i++){adapter.deleteItem(position);}

then in your adapter implement removeItem function: 然后在您的适配器中实现removeItem函数:

public void deleteItem(int index) {
    Dataset.remove(index);
    notifyItemRemoved(index);
}

You can remove a single item in RecyclerView adapter with: 您可以使用以下方法在RecyclerView适配器中删除单个项目:

List<YourData> list;

// position of your data in the list.
private removeItem(int position) {
  list.remove(position);
  notifyItemRemoved(position);
}

But you can't use it if you need to remove multiple items sequentially. 但是,如果需要顺序删除多个项目,则不能使用它。 The following won't work: 以下内容不起作用:

removeItem(3);
removeItem(36);
removeItem(54);

because the list index has been changed after the first call of removeItem() . 因为在第一次调用removeItem()之后,列表索引已更改。

So, you need to depend on an Id for your data. 因此,您需要依靠一个ID来获取数据。 For example, with the following User class: 例如,使用以下用户类:

public class User {
  private long id;
  private String name;

  // constructor
  // setter
  // getter

}

you can remove multiple items sequentially by checking the id with the following method: 您可以使用以下方法通过检查ID来依次删除多个项目:

// list of your User
List<User> users;

// id is your User id
private removeItem(int id) {
  for(int i = 0; i < users.size(); i++) {
    User user = users.get(i)
    if(user.getId() == id) {
      users.remove(i);
      break;
    }
  }
}

which can be used if you know the id: 如果您知道ID,可以使用它:

removeItem(3);
removeItem(36);
removeItem(54);

Of course, you can add another method to remove items by using a list of id: 当然,您可以使用ID列表添加另一种方法来删除项目:

private removeItems(List<Integer> ids) {
  for(Integer id: ids) {
    removeItem(id);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM