How to scroll tablayout programmatically - Android

前端 未结 13 2185
终归单人心
终归单人心 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:48

    write this method in your custom tablayout (Your own layout which extends tablayout). So, in future you can use this method whenever you need instad of code duplication

    public void selectTabAt(int tabIndex) {
            if (tabIndex >= 0 && tabIndex < getTabCount() && getSelectedTabPosition() != tabIndex) {
                final Tab currentTab = getTabAt(tabIndex);
                if (currentTab != null) {
                    this.post(new Runnable() {
                        @Override
                        public void run() {
                            currentTab.select();
                        }
                    });
                }
            }
        }
    

    If you don't want yo use CustomLayout. you can just do this

    final Tab currentTab = mTabLayout.getTabAt(tabIndex);
    if(currentTab != null){
         mTabLayout.post(new Runnable() {
                        @Override
                        public void run() {
                            currentTab.select();
                        }
                    });
    }
    

提交回复
热议问题