繁体   English   中英

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

[英]Remove items from specific positions on recyclerView

我有一个recyclerView和一个List<> ,其中包含一些随机位置

我要做的就是从列表中存储的position删除recyclerView项目。

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

从您的活动中,您可以循环显示要删除的项目位置列表

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

然后在您的适配器中实现removeItem函数:

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

您可以使用以下方法在RecyclerView适配器中删除单个项目:

List<YourData> list;

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

但是,如果需要顺序删除多个项目,则不能使用它。 以下内容不起作用:

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

因为在第一次调用removeItem()之后,列表索引已更改。

因此,您需要依靠一个ID来获取数据。 例如,使用以下用户类:

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

  // constructor
  // setter
  // getter

}

您可以使用以下方法通过检查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;
    }
  }
}

如果您知道ID,可以使用它:

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

当然,您可以使用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