I have a recyclerView
and a List<>
which contains some random position
All i want to do is remove recyclerView
item from position
stored in the list.
更好的方法是从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:
public void deleteItem(int index) {
Dataset.remove(index);
notifyItemRemoved(index);
}
You can remove a single item in RecyclerView adapter with:
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()
.
So, you need to depend on an Id for your data. 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:
// 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:
removeItem(3);
removeItem(36);
removeItem(54);
Of course, you can add another method to remove items by using a list of id:
private removeItems(List<Integer> ids) {
for(Integer id: ids) {
removeItem(id);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.