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

后端 未结 12 1428
野的像风
野的像风 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:55

    I also needed to execute code after my recycler view finished inflating all elements. I tried checking in onBindViewHolder in my Adapter, if the position was the last, and then notified the observer. But at that point, the recycler view still was not fully populated.

    As RecyclerView implements ViewGroup, this anwser was very helpful. You simply need to add an OnGlobalLayoutListener to the recyclerView:

    View recyclerView = findViewById(R.id.myView);
    recyclerView
        .getViewTreeObserver()
        .addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    // At this point the layout is complete and the
                    // dimensions of recyclerView and any child views 
                    // are known.
                    recyclerView
                        .getViewTreeObserver()
                        .removeOnGlobalLayoutListener(this);
                }
            });
    

提交回复
热议问题