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

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

    I have been struggling with trying to remove OnGlobalLayoutListener once it gets triggered but that throws an IllegalStateException. Since what I need is to scroll my recyclerView to the second element what I did was to check if it already have children and if it is the first time this is true, only then I do the scroll:

    public class MyActivity extends BaseActivity implements BalanceView {
        ...
        private boolean firstTime = true;
        ...
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            ...
    
            ViewTreeObserver vto = myRecyclerView.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (myRecyclerView.getChildCount() > 0 && MyActivity.this.firstTime){
                        MyActivity.this.firstTime = false;
                        scrollToSecondPosition();
                    }
                }
            });
        }
        ...
        private void scrollToSecondPosition() {
            // do the scroll
        }
    }
    

    HTH someone!

    (Of course, this was inspired on @andrino and @Phatee answers)

提交回复
热议问题