我尝试从 Adapter 类(onBindViewHolder
方法)刷新整个 RecyclerView。
如果我点击列表中的一个项目,我希望这个项目的参数会改变。
这样做的最佳方法是什么?
Adapter
类中的 onBindViewHolder
方法:
@Override
public void onBindViewHolder(@NonNull final StoreRecyclerViewAdapter.ViewHolder holder, final int position) {
// Get the image of the Player item
Glide.with(context)
.asBitmap()
.load(allPlayers.get(position))
.into(holder.playerInStore);
// Get the price of the Player of the item
holder.playerPrice.setText(allPrices.get(position).toString());
// Get the status of the Player of the item
holder.status = allStatus.get(position);
// If Player status is "CLOSED", get the closed lock image of the item
if (allStatus.get(position).equals("CLOSE")) {
Glide.with(context)
.asBitmap()
.load(close.getStatusPic())
.into(holder.playerLock);
// The user can purchase the item
holder.layoutStore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int price = Integer.valueOf(holder.playerPrice.getText().toString());
boolean canPurchase = StoreLogic.getStoreLogic().canPurchase(price);
if (canPurchase) {
String purchaseSuccessfully = "purchase succcessfully :)";
Toast.makeText(context, purchaseSuccessfully, Toast.LENGTH_SHORT).show();
// update list details
//****************** REFRESH LIST *******************
}
else {
String purchaseFailed = "not enough coins :(";
Toast.makeText(context, purchaseFailed, Toast.LENGTH_SHORT).show();
}
}
});
}
// If Player status is "OPEN", get the open lock image of the item
else {
Glide.with(context)
.asBitmap()
.load(open.getStatusPic())
.into(holder.playerLock);
// The user cannot purchase the item
holder.layoutStore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "already available", Toast.LENGTH_SHORT).show();
}
});
}
}
RecyclerView
类中的initRecyclerView
方法:
protected void initRecyclerViewForAllPlayers() {
RecyclerView recyclerView = findViewById(R.id.rv_store);
StoreRecyclerViewAdapter adapter = new StoreRecyclerViewAdapter(this, allPlayers, allPrices, allStatus, open, close);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager((this)));
}
找到解决方案
不幸的是,评论中的解决方案都没有帮助,方法 notifyDataSetChanged()
、 notifyItemChanged(position)
没有刷新数据。
也许它会在将来帮助某人:
为了刷新整个列表,我访问了 Activity (Store
) 中的 init 方法 (initImageBitmapsForAllPlayers
),并从 onBindViewHolder
调用它在适配器中:
if (context instanceof Store) {
notifyItemChanged(position);
((Store) context).initImageBitmapsForAllPlayers();
}
最佳答案
调用以下方法刷新内部适配器:
notifyDataSetChanged()
内部 Activity
if (recyclerView.getAdapter() != null) {
recyclerView.getAdapter().notifyDataSetChanged();
}
关于java - 从 Adapter 中刷新整个 RecyclerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57120079/