How to scroll tablayout programmatically - Android

前端 未结 13 2131
终归单人心
终归单人心 2021-02-07 00:31

I have created 30 scrollable tabs using tablayout.

So first three tabs are visible on screen and rest of them are invisible which can be scroll using swipe gesture.

13条回答
  •  隐瞒了意图╮
    2021-02-07 00:50

    Are you calling tab.select() before the TabLayout and its children have actually been measured and drawn? If so, your TabLayout won't animate to the selection with tab.select() (or Kayvan N's suggestion of scrollTo()). Using a Handler will probably work, but that's not an ideal solution.

    Provided the layout hasn't been laid out yet, a ViewTreeObserver will allow you to move to your selected tab after the layout process is finished.

    private void scrollToTabAfterLayout(final int tabIndex) {
        if (getView() != null) {
            final ViewTreeObserver observer = mTabLayout.getViewTreeObserver();
    
            if (observer.isAlive()) {
                observer.dispatchOnGlobalLayout(); // In case a previous call is waiting when this call is made
                observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            observer.removeOnGlobalLayoutListener(this);
                        } else {
                            //noinspection deprecation
                            observer.removeGlobalOnLayoutListener(this);
                        }
    
                        mTabLayout.getTabAt(tabIndex).select();
    
                    }
                });
            }
        }
    }
    

    Please comment if you have any suggestions.

提交回复
热议问题