0

I am altering a recyclerview and would like to be notified of when that update is finished. I read How to know when the RecyclerView has finished laying down the items? that you are notified in the callback to addOnGlobalLayoutListener, but that is called too many times unless you add the last line.

Here is what I tried:

my_rv.viewTreeObserver.addOnGlobalLayoutListener {
     calculate(myAdapter.getItems())
     my_rv.viewTreeObserver.removeOnGlobalLayoutListener(this)
}

in order for the last line to compile, my fragment needs to override onGlobalLayout. What am I supposed to put in onGlobalLayout? I never see that callback even called.

HukeLau_DABA
  • 2,384
  • 6
  • 33
  • 51

1 Answers1

0

It's because in your calculate method you change the layout, like setting text, setting image resource, etc. so in the first call you need to remove the listener to avoid listening to the next GlobalLayout events.

and it is better to remove removeOnGlobalLayoutListener in first line:

my_rv.viewTreeObserver.addOnGlobalLayoutListener {
 my_rv.viewTreeObserver.removeOnGlobalLayoutListener(this)
 calculate(myAdapter.getItems())
}
  • thanks, but in my calculate method I am not changing the layout. I am concatenating attributes in the item list actually. Why does calculate still get called so many times if I do this? Also, since "this" refers to my fragment it needs to override onGlobalLayout<---what goes inside that method? – HukeLau_DABA Jun 02 '19 at 11:40
  • can you send calculate method body? – Omid Faraji Jun 03 '19 at 06:11