我的 RecyclerView 上的每个项目都有一个具有三种状态的按钮:OPEN、LOADING 和 CLOSED。
最初所有按钮都处于打开状态。单击按钮时,状态更改为 LOADING 并在后台执行网络调用。网络调用成功后,按钮状态应该变为CLOSED。
所以在我的适配器中我使用了以下内容:
holder.button.setOnClickListener(v -> {
holder.state = LOADING;
notifyItemChanged(holder.getAdapterPosition()); /* 1 */
callNetwork(..., () -> {
/* this is the callback that runs on the main thread */
holder.state = CLOSED;
notifyItemChanged(holder.getAdapterPosition()); /* 2 */
});
});
LOADING 状态始终在 /* 1 */ 处正确显示,因为 getAdapterPosition() 为我提供了正确的位置。
但是,按钮的 CLOSED 状态永远不会可视化,因为 /* 2 */ 处的 getAdapterPosition 总是返回 -1。
在这种情况下,我可能会错误地理解 getAdapterPosition()。
如何在回调中刷新项目的外观?
最佳答案
来自docs :
Note that if you've called
notifyDataSetChanged(), until the next layout pass, the return value of this method will beNO_POSITION
NO_POSITION 是一个常量,其值为-1。这或许可以解释为什么您会在此处获得 -1 的返回值。
无论如何,为什么不在底层数据集中找到模型的位置,然后调用notifyItemChanged(int position)?您可以将模型保存为 holder 中的一个字段。
例如:
public class MyHolder extends RecyclerView.ViewHolder {
private Model mMyModel;
public MyHolder(Model myModel) {
mMyModel = myModel;
}
public Model getMyModel() {
return mMyModel;
}
}
holder.button.setOnClickListener(v -> {
holder.state = LOADING;
notifyItemChanged(holder.getAdapterPosition());
callNetwork(..., () -> {
/* this is the callback that runs on the main thread */
holder.state = CLOSED;
int position = myList.indexOf(holder.getMyModel());
notifyItemChanged(position);
});
});
或者,如果位置为 -1,您也可以忽略,如下所示:
holder.button.setOnClickListener(v -> {
holder.state = LOADING;
int preNetworkCallPosition = holder.getAdapterPosition();
if (preNetworkCallPosition != RecyclerView.NO_POSITION) {
notifyItemChanged(preNetworkCallPosition);
}
callNetwork(..., () -> {
/* this is the callback that runs on the main thread */
holder.state = CLOSED;
int postNetworkCallPosition = holder.getAdapterPosition();
if (postNetworkCallPosition != RecyclerView.NO_POSITION) {
notifyItemChanged(postNetworkCallPosition);
}
});
});
关于android - RecyclerView getAdapterPosition() 在回调中返回 -1,因此我无法显示项目的新外观,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36259716/