How to know when the RecyclerView has finished laying down the items?

后端 未结 12 1471
野的像风
野的像风 2020-11-29 20:06

I have a RecyclerView that is inside a CardView. The CardView has a height of 500dp, but I want to shorten this height if the Re

12条回答
  •  我在风中等你
    2020-11-29 20:48

    Working modification of @andrino anwser.

    As @Juancho pointed in comment above. This method is called several times. In this case we want it to be triggered only once.

    Create custom listener with instance e.g

    private RecyclerViewReadyCallback recyclerViewReadyCallback;
    
    public interface RecyclerViewReadyCallback {
        void onLayoutReady();
    }
    

    Then set OnGlobalLayoutListener on your RecyclerView

    recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (recyclerViewReadyCallback != null) {
                        recyclerViewReadyCallback.onLayoutReady();
                    }
                    recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            });
    

    after that you only need implement custom listener with your code

    recyclerViewReadyCallback = new RecyclerViewReadyCallback() {
                 @Override
                 public void onLayoutReady() {
                     //
                     //here comes your code that will be executed after all items are laid down
                     //
                 }
    };
    

提交回复
热议问题