android - 当我删除项目时,Recyclerview 没有更新
问题描述
我有一个购物车,可以在其中添加产品,但我遇到了问题。当我按下按钮删除项目时,在调用 notifydatachanged() 后回收站视图不会更新。当我再次导航到我的购物车时,该项目不存在,因为已删除。但是当我在购物车活动中时,我不想看到直接。这是我的适配器:
holder.removeProduct.setOnClickListener(v -> {
SharedPreferences preferences = mContext.getSharedPreferences(ITEMS_PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = preferences.edit();
Gson gson = new Gson();
String json = preferences.getString("artikujtShporta", "");
ArrayList<Artikujt> artikullObject = gson
.fromJson(json, new TypeToken<ArrayList<Artikujt>>(){}.getType());
if (artikullObject != null) {
int indexToRemove;
for(int i = 0 ; i < artikullObject.size(); i++){
if(artikullObject.get(i).getId().equals(artikulli.getId())) {
indexToRemove = i;
artikullObject.remove(indexToRemove);
notifyItemRemoved(indexToRemove);
String jsonString = gson.toJson(artikullObject);
mEditor.putString("artikujtShporta", jsonString);
mEditor.apply();
}
}
}
});
在我的片段中:
SharedPreferences preferences = Objects.requireNonNull(getContext())
.getSharedPreferences(ITEMS_PREF, Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = preferences.getString("artikujtShporta", "");
cartItems = gson.fromJson(json, new TypeToken<ArrayList<Artikujt>>(){}.getType());
basketAdapter = new BasketAdapter(cartItems, getContext());
mRecyclerView = mView.findViewById(R.id.basket_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
mRecyclerView.setAdapter(basketAdapter);
//basketAdapter.clear();
//basketAdapter.addAll(cartItems);
basketAdapter.notifyDataSetChanged();
解决方案
创建一个IShoppingCart
接口,该接口将由您的Fragment
. 我们希望将逻辑保留在Fragment
. (我个人会将这个逻辑转移到,ViewModel
但这将是一个切线。)
购物车
interface IShoppingCart {
fun addItemToCart(item: CartItem): Boolean
fun removeItemToCart(itemId: String): Boolean
/**
* Feel free to add more functionality
*/
}
现在,通过组合将您的片段传递给您的 RecyclerViewAdapter。
回收器视图适配器
ShoppingCartAdapter(val contract: IShoppingCart) : RecyclerView.Adapter<ViewHolder>() {
.
.
.
}
现在你可以在你的ViewHolder
类中使用这个引用,因为它们可能被定义为Inner Classes.
视图持有者
holder.removeProduct.setOnClickListener(v -> {
// This will kick in the code that lies in the Fragment
contract.removeItemToCart(viewHolder.itemView.id)
});
现在在你的Fragment
,里面removeItemToCart(val itemId)
,只需删除item
给定的itemId
并调用notifyDataSetChanged()
。
分段
fun DeleteItemToCart(itemId: String) {
dataset.removeItemWithItemId(itemId)
notifyDataSetChanged()
}
按照这种方法,您不需要通知适配器整个数据集发生了变化,因为它没有发生变化。你可以简单地告诉适配器只有一个元素的位置改变了(因为它被删除了)notifyItemRemoved(position: Int)
。
推荐阅读
- informix - 如何在当前会话中获得隔离级别?
- vb.net - 变量“GetTransNo”在被赋值之前被使用。运行时可能会导致空引用异常”
- json - 临时存储大量 JSON 文件的最佳方法?
- django - Django Form 进行计算
- c++ - 多定义链接 c++ 项目构建与 cmake
- c# - 项目 SDK 为 Microsoft.NET.Sdk.Web 时无法添加纯 C# 文件
- sass - 将多个 Dart SCSS 文件合并为一个
- javascript - Javascript Websockets在页面卸载时断开连接
- javascript - Javascript函数被截断?
- reactjs - 使用 refs 解耦回调安全吗?