Reputation: 4044
I am create and using custom RecyclerView in my application. I need to call getChildAt(0).getWidth()
before any working to save first item width in class field. For that I need to catch when data loading in adapter (otherwise getChildAt(0) will returns null).
How to catch data loading event inside custom RecyclerView?
Upvotes: 7
Views: 5941
Reputation: 56
Use getViewTreeObserver().addOnGlobalLayoutListener to receive a callback when the children have been layout on the screen.
Also don't forget add remove Observer Listener after call first time, like this to avoid repetition call.
View recyclerView = findViewById(R.id.myView);
recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
recyclerView
.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
}
});
Upvotes: 2
Reputation: 39846
RecyclerView is already calling registerAdapterDataObserver
and it's unregister counterpart on the adapter the supplied adapter.
This observer have several callbacks to let the Recycler know when data is added, removed or changed. You should take advantage of those.
Also, the moment the adapter changes the data, it's not the same moment the views are created/layout on the screen. You might have to call getViewTreeObserver().addOnGlobalLayoutListener
to receive a callback when the children have been layout on the screen.
Hope it helps, happy coding.
Upvotes: 5