BArtWell
BArtWell

Reputation: 4044

How to know when data is loaded inside custom RecyclerView?

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

Answers (2)

Mohamed Nasser
Mohamed Nasser

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

Budius
Budius

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

Related Questions