Each item on my RecyclerView has a button that has three states: OPEN, LOADING, and CLOSED.
Initially all the buttons are in the OPEN state. When a button is clicked, the state is changed to LOADING and a network call is performed in the background. After the network call succeeds, the button state should be changed to CLOSED.
So in my adapter I used the following:
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 */
});
});
The LOADING state is always visualized correctly at /* 1 */
because getAdapterPosition()
gives me the correct position.
However, the CLOSED state of the button is never visualized, because getAdapterPosition
at /* 2 */
always returns -1
.
I might understand getAdapterPosition()
wrongly in this case.
How do I refresh the appearance of an item on a callback?
getAdapterPosition()
. why do you need holder there? – Loup/* 1 */
in a variable then use that variable instead of callinggetAdapterPosition
again? – YarecallNetwork
is a background process right? That means that the first call tonotifyItemChanged
will update your adapter which will result in-1
for the second call ofnotifyItemChanged
– Yare