Nelson Silva
Nelson Silva

Reputation: 439

Get tab title onCreate tab

I need to get the tab title when I first open my app. I can do it when the user changes the tab and save it in shared pref by using onTabSelected but if the user does not change the tab, I don't know how to access the title. Im using this:

tabLayout.addOnTabSelectedListener(
        new ViewPagerOnTabSelectedListener(myViewPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                String dataTab = tab.getText().toString();
                SharedPreferences.Editor editor = getSharedPreferences("PREFERENCIAS", MODE_PRIVATE).edit();
                editor.putString("DATA", dataTab);
                editor.apply();
            }
        });

Upvotes: 0

Views: 455

Answers (3)

Evstropov V
Evstropov V

Reputation: 520

You can use next method for get tab title:

private String getTabText(Integer tabPosition){
        TabLayout.Tab tab = tabLayout.getTabAt(tabPosition);
        return tab.getText().toString();
}

Upvotes: 0

Mohit Charadva
Mohit Charadva

Reputation: 2613

You can use below code to get the title of the selected tab.

int selectedTabIndex = tabLayout.getSelectedTabPosition();
TabLayout.Tab tab = tabLayout.getTabAt(selectedTabIndex);
String tabTitle = tab.getText();

Upvotes: 0

Ahmed Hegazy
Ahmed Hegazy

Reputation: 12605

You can do that after setting up the TabLayout by using

tabLayout.getTabAt(0).getText()

Upvotes: 1

Related Questions