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.
The above answer wouldn't work because first As agirardello mentioned you should not use mTabLayout.getWidth()
since it doesn't return what we need (which is the position of the child you want to scroll to) and the updated solution doesn't always work because of a bug in TabLayout (reported here) but a work around is simple.
The tabs on the tabLayout are not direct children of the TabLayout so we need to go one level deeper using
((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(YOUR_DESIRED_TAB_INDEX).getRight()
the only child of tabLayout is a TabLayout.SlidingTabStrip
which is also a ViewGroup
and getRight()
will give us the right most position of our desired tab view. Thus scrolling to that position will give us what we desire. Here is a complete code:
int right = ((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(4).getRight();
mTabLayout.scrollTo(right,0);
mTabLayout.getTabAt(4).select();
NOTE: Make sure you are calling these methods after the layout has been drown (like onResume and not onCreate)
Hope this helps.