簡體   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