Android Tab Help. How to set 2nd tab as default when app opens?
Asked Answered
U

4

6

I have created an app with 3 tabs. The app works fine but I want the 2nd tab to be selected and loaded when the app opens. How can I set that?

Here is my code :

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TabHost tabHost = getTabHost();



        // Tab for Home
        TabSpec homespec = tabHost.newTabSpec("Home");
        // setting Title and Icon for the Tab
        homespec.setIndicator("Home",getResources().getDrawable(R.drawable.icons_home_tab));
        Intent photosIntent = new Intent(this, HomeActivity.class);
        homespec.setContent(photosIntent);

        // Tab for Child
        TabSpec childspec = tabHost.newTabSpec("Child");
        childspec.setIndicator("Child",getResources().getDrawable(R.drawable.icons_child_tab));
        Intent homeIntent = new Intent(this, ChildActivity.class);
        childspec.setContent(homeIntent);

        // Tab for Account
        TabSpec accspec = tabHost.newTabSpec("Account");
        accspec.setIndicator("Account",getResources().getDrawable(R.drawable.icons_account_tab));
        Intent accIntent = new Intent(this, AccountActivity.class);
        accspec.setContent(accIntent);

        // Adding all TabSpec to TabHost
        tabHost.addTab(homespec); // Adding home tab
        tabHost.addTab(childspec); // Adding child tab
        tabHost.addTab(accspec); //Adding account tab
        }
Unexpressive answered 18/4, 2013 at 6:2 Comment(2)
tabHost.setCurrentTab(1); as your tabs are 0-1-2Kenakenaf
val tabs = findViewById<TabLayout>(R.id.tabs) tabs.getTabAt(1)!!.select() in kotlin (1 can be any index of your preference)Schlimazel
S
13

Use this method to set the current tab after you added tab in tabHost

tabHost.setCurrentTab(1);  // here pass the tab index its starting from 0
Support answered 18/4, 2013 at 6:4 Comment(0)
L
3

use tabHost.setCurrentTab(1); in your onCreate

Lebanon answered 18/4, 2013 at 6:4 Comment(0)
C
1
public override void OnResume() 
    {
        base.OnResume();
        tabHost.CurrentTab = 1; //index of the tab you want to set to default.
    }

Override the OnResume() and assign the CurrentTab property of tabHost to the index of the tab you want to.

Courtroom answered 1/11, 2016 at 22:31 Comment(1)
tabHost.setCurrentTab() within the OnResume method worked for meLewislewisite
F
1

There are some difficulties if you have fragments. The hack is to make tab selection delayed. See code in this answer.

Fetal answered 11/10, 2018 at 5:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.