So this question is regarding the use of doOnLayout and the undesired effect it has when the view that is using it is being recycled.
So far I have been using this function to perform an action when the view is laid out so that I know the view has some measures. This is specially useful whenthe view measures depend on some constraints rather than having a fixed size. Recently I notice that the lambda I pass to the doOnLayout is not being executed when the view is being recycled. So let's say that I have a list of items and then at some point the recyclerView will reuse some views to render the items.
This is the code inside the doOnLayout
if (isLaidOut && !isLayoutRequested) {
action(this)
} else {
doOnNextLayout { action(it) }
}
I have been debugging the logic I have and I found out that when the view is being recycled, isLaidOut is false, the view itself has measures and isLayoutRequested is false.
On top of that, the view is not being requested a layout (and that matches with the fact that isLayoutRequested is false), but because of this then the action I pass is not executed (based on the logic from doOnLayout, the action is being passed to doOnNextLayout)
From my understanding, the fact that the view has already measures make sense considering the view is being recycled. isLayoutRequested I guess it makes sense too also based on the same reasons but I am not 100% sure. But what I do not understand is why isLaidOut is being false here.
So if I have to translate this, I would say that recyclerView, when it recycles a view, it will not request a new layout but also will keep the value isLayout to false, so in the end it translates as the layout is never laid out which is not true.
I was wondering if any of you has experienced this behaviour and if this is correct or is it some sort of a bug in the android library?. The version of recyclerView I am using is 1.4.0.
I can come up with some workaround but to me, it looks quite dangerous to use the doOnLayout api when it some component like the recyclerView has unexpected behaviours.