How to scroll tablayout programmatically - Android How to scroll tablayout programmatically - Android android android

How to scroll tablayout programmatically - Android


I found the solution.

First I had found the width of tablayout and scroll it's x position to width and than called the select() method of last tab.

And it works fine.

Below is the code.

mTabLayout.setScrollX(mTabLayout.getWidth());mTabLayout.getTabAt(lastTabIndex).select();

Updated:

If above is not working you can use the below code as well, it is also working fine.

new Handler().postDelayed(        new Runnable() {            @Override public void run() {                mTabLayout.getTabAt(TAB_NUMBER).select();            }        }, 100);


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();                    }                });}


I found this solution for me:

    TabLayout tabLayout = activity.getTabLayout();    tabLayout.setSmoothScrollingEnabled(true);    tabLayout.setScrollPosition(targetChannelPosition, 0f, true);

Also, if you receive this error: "Only the original thread that created a view hierarchy can touch its views.", you can use this code, in order to run on Ui thread:

    // find a way to get the activity containing the tab layout    TabLayout tabLayout = activity.getTabLayout();    activity.runOnUiThread(new Runnable()    {        @Override        public void run()        {            TabLayout.Tab tab = tabLayout.getTabAt(targetChannelPosition);            tab.select();        }    });