[Android] Cập nhật dữ liệu trong RecyclerView

Đăng bởi: Admin | Lượt xem: 2787 | Chuyên mục: Android

Hướng dẫn cách cập nhật dữ liệu trong RecyclerView Android


Tổng quan

Quá trình thay đổi dữ liệu của adapter luôn bao gồm 2 bước chính

1. Cập nhật bộ dữ liệu

2. Thông báo cho adapter dữ liệu đã thay đổi

Các ví dụ dưới đây sẽ hướng dẫn bạn cách thực hiện điều đó: 

Thêm một item

Thêm “Pig” ở index 2

String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);

Thêm nhiều item

Thêm 3 item ở index 2

ArrayList<String> items = new ArrayList<>();
items.add("Pig");
items.add("Chicken");
items.add("Dog");
int insertIndex = 2;
data.addAll(insertIndex, items);
adapter.notifyItemRangeInserted(insertIndex, items.size());

Xóa một item

Xóa “Pig” khỏi danh sách

int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);

Xóa nhiều item

Xóa “Camel” and “Sheep” khỏi danh sách

int startIndex = 2; // inclusive
int endIndex = 4;   // exclusive
int count = endIndex - startIndex; // 2 items will be removed
data.subList(startIndex, endIndex).clear();
adapter.notifyItemRangeRemoved(startIndex, count);

Xóa tất cả các item

Xóa toàn bộ danh sách

data.clear();
adapter.notifyDataSetChanged();

Thay danh sách cũ bằng danh sách mới

Xóa danh sách cũ và thêm một danh sách mới

// clear old list
data.clear();

// add new list
ArrayList<String> newList = new ArrayList<>();
newList.add("Lion");
newList.add("Wolf");
newList.add("Bear");
data.addAll(newList);

// notify adapter
adapter.notifyDataSetChanged();

Cập nhật một item

Sửa item "Sheep" thành "I like Sheep"

String newValue = "I like sheep.";
int updateIndex = 3;
data.set(updateIndex, newValue);
adapter.notifyItemChanged(updateIndex);

Di chuyển một item

Di chuyển "Sheep" từ vị trí 3 lên vị trí 1

int fromPosition = 3;
int toPosition = 1;
// update data array
String item = data.get(fromPosition);
data.remove(fromPosition);
data.add(toPosition, item);
// notify adapter
adapter.notifyItemMoved(fromPosition, toPosition);

Chú ý

Nếu bạn dùng notifyDataSetChanged() thì sẽ không có animation. Đây cũng có thể là một hoạt động tốn kém và dư thừa, vì vậy không nên sử dụng notifyDataSetChanged () nếu bạn chỉ cập nhật một hoặc một số item.

Cảm ơn các bạn đã đọc bài viết. Chào thân ái và quyết thắng!

Link bài viết gốc: https://medium.com/@suragch/updating-data-in-an-android-recyclerview-842e56adbfd8

vncoder logo

Theo dõi VnCoder trên Facebook, để cập nhật những bài viết, tin tức và khoá học mới nhất!



Khóa học liên quan

Khóa học: Android

Học Kotlin cơ bản
Số bài học:
Lượt xem: 17103
Đăng bởi: Admin
Chuyên mục: Android

Học lập trình Flutter cơ bản
Số bài học:
Lượt xem: 55244
Đăng bởi: Admin
Chuyên mục: Android

Lập trình Android cơ bản
Số bài học:
Lượt xem: 22244
Đăng bởi: Admin
Chuyên mục: Android