Ran*_*ku' 7 android android-adapter android-recyclerview
我的RecyclerView上的每个项目都有一个按钮,它有三种状态:OPEN,LOADING和CLOSED.
最初所有按钮都处于OPEN状态.单击按钮时,状态将更改为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 */
});
});
Run Code Online (Sandbox Code Playgroud)
LOADING状态总是可以正确显示,/* 1 */因为getAdapterPosition()它给了我正确的位置.
然而,按钮的关闭状态从来没有显现,因为getAdapterPosition在/* 2 */总是返回-1.
getAdapterPosition()在这种情况下,我可能会错误地理解.
如何在回调中刷新项目的外观?
Mid*_*fko 18
来自文档:
请注意,如果您已调用
notifyDataSetChanged(),则在下一个布局过程之前,此方法的返回值将为NO_POSITION
NO_POSITION是一个常量,其值为-1.这可以解释为什么你在这里获得-1的返回值.
在任何情况下,为什么不在基础数据集中找到模型的位置然后调用notifyItemChanged(int position)?您可以将模型保存为持有者中的字段.
例如:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4638 次 |
| 最近记录: |