Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll tablayout programmatically - Android

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 problem is when I am selecting last tab programmatically but it is not get visible (tab layout not get scrolled to last tab).

How can I make tablayout to scroll to last tab?

like image 439
Mohit Charadva Avatar asked Jul 16 '15 07:07

Mohit Charadva


People also ask

How to set Scroll in tablayout Android?

I dived into Tab. select(), and found Android uses Tablayout. setScrollPosition() to do this scrolling. And in onCreate() the widgets have not been measured, you need to postpone the call until layout is complete.

How do you Tablayout on Android?

This example demonstrates how do I create a Tab Layout in android app. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 3 − Add the following code to res/layout/activity_main. xml.


1 Answers

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); 
like image 176
Mohit Charadva Avatar answered Sep 26 '22 01:09

Mohit Charadva