Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android TabLayout select first Tab on Startup

I'm using TabLayout from Android Design Library. I have multiple tabs and each Tab has an action when it is selected. So I have an attribute startSelection, which performs

tabLayout.getTabAt(startSelection).select();

This selects the tab and performs the action for this tab. It works fine for each Tab except the first one, which is automatically selected on Startup without (!) performing the action. Does anyone have a solution for this?

I don't want to use the onTabReselected method, because this causes another behaviour of the TabLayout. Also selecting the second tab and selecting the first tab afterwards is no good solution.

Best regards

like image 290
user2331454 Avatar asked May 06 '16 12:05

user2331454


People also ask

How do I select a tab in Android?

If you know the index of the tab you want to select, you can do it like so: TabLayout tabLayout = (TabLayout) findViewById(R. id. tabs); TabLayout.


1 Answers

I had a similar problem with a custom tab layout I was implementing, when starting the activity the first tab wouldn't appear in the selected state but tab 2,3,4... would when auto-selected on startup.

The solution that helped me was in onResume(), quickly select the second tab then return to the first tab.

    @Override
    protected void onResume() {
        super.onResume();
        mTabLayout.getTabAt(1).select();
        mTabLayout.getTabAt(0).select();
    } 
like image 158
Cameron A Avatar answered Sep 23 '22 23:09

Cameron A