Get tab title onCreate tab - android

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();
}
});

You can do that after setting up the TabLayout by using
tabLayout.getTabAt(0).getText()

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();

You can use next method for get tab title:
private String getTabText(Integer tabPosition){
TabLayout.Tab tab = tabLayout.getTabAt(tabPosition);
return tab.getText().toString();
}

Related

How to get Tab's parent (TabLayout) from TabSelectedListener

I have two TabLayouts on the same fragment and each of them holds two tabs:
TabLayout studentsTab = view.findViewById(R.id.students_tab);
studentsTab.addTab(studentsTab.newTab().setText("one"));
studentsTab.addTab(studentsTab.newTab().setText("two"));
studentsTab.setTag("students");
TabLayout teachersTab = view.findViewById(R.id.teachers_tab);
teachersTab.addTab(teachersTab.newTab().setText("one"));
teachersTab.addTab(teachersTab.newTab().setText("two"));
teachersTab.setTag("teachers");
and instead of creating two setOnTabSelectedListener listeners i've implemented TabLayout.OnTabSelectedListener by :
studentsTab.setOnTabSelectedListener(this);
teachersTab.setOnTabSelectedListener(this);
and now i have this method:
#Override
public void onTabSelected(TabLayout.Tab tab) {
// detect which TabLayout?
}
and I want to figure which tab triggered the tab selection. Is it studentsTab or teachersTab?
I tried to check if tab.getTag().equals("students") but the tab.getTag() is null.
When i debug the app i have the TabLayout on tab.mParent but it's not accessible.
I couldn't find a way to do it. Any help to find the parent would be appreciated.
You can set a tag associated with your tabs before you add them to the TabLayout. If you add a tag of "student" or "teacher" to the correct tab, then you can reference that information in the onTabSelected().
Check out the docs: TabLayout specifically looking at the getTag() and setTag().
Try setting contentDescription for each tab like this
for(int i=0; i<studentsTab.getTabCount; i++) {
TabLayout.Tab tab = studentsTab.getTabAt(i);
tab.setContentDescription("Text");
}
And then, in the onTabSelected method get the contentDescription
public void onTabSelected(TabLayout.Tab tab) {
tab.getContentDescription();
}

How to move to a specific tab from an activity in android

I am working on the following screen named FriendListActivity:
As you can see here , I am 3 tabs named CHAT,GROUPS and CONTACTS .Each tab is displaying some contents.For example Groups Tab is displaying the number of groups.On clicking each Group ,Group Chat Screen is opened .Now In Group Chat screen ,i have a toolbar .Consider the following code:
Toolbar toolbarGroupChat = (Toolbar) findViewById(R.id.toolbarGroupChat);
setSupportActionBar(toolbarGroupChat);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(upperCase(group_name));
//ViewPager
viewPager = (ViewPager) findViewById(R.id.viewPager);
//Initializing PagerAdapter
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
PagerAdapter.java
public class PagerAdapter extends FragmentStatePagerAdapter {
private int noOfTabs;
public PagerAdapter(FragmentManager fm, int noOfTabs) {
super(fm);
this.noOfTabs = noOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
ChatFragment chatFragment = new ChatFragment();
return chatFragment;
case 1:
GroupsFragment groupsFragment = new GroupsFragment();
return groupsFragment;
case 2:
ContactsFragment contactsFragment = new ContactsFragment();
return contactsFragment;
default:
return null;
}
}
#Override
public int getCount() {
return noOfTabs;
}
}
On clicking the arrow on the toolbar ,my application is moved to the screen containing three tabs.My problem is current selected tab is always CHAT tab ,when i am moving from an activity to FriendListActivity .When i am moving from Group Chat Screen to FriendListActivity,the current selected tab should be GROUPS Tab.
Solved.
Edited Working Code:
When we are moving from an Activity to a specific tab ,We need to pass the TAb number using intents from the Activity.Use the following code for handling click on the back button of the Toolbar .Override the getSupportParentActivityIntent() method:
public Intent getSupportParentActivityIntent() {
final Bundle bundle = new Bundle();
final Intent intent = new Intent(this, FriendsListActivity.class);
bundle.putString("TabNumber", tab_number);
intent.putExtras(bundle);
return intent;
}
Now inside the activity containing 3 tabs,use the following code:
final Intent intent = getIntent();
if (intent.hasExtra("TabNumber")) {
String tab = intent.getExtras().getString("TabNumber");
Log.e("TabNumberFriendList",tab);
switchToTab(tab);
}
public void switchToTab(String tab){
if(tab.equals("0")){
viewPager.setCurrentItem(0);
}else if(tab.equals("1")){
viewPager.setCurrentItem(1);
}else if(tab.equals("2")){
viewPager.setCurrentItem(2);
}
}
Use the setCurrentItem(int position) method of your ViewPager object to move to a specific tab.
You might have created a tabHost, so when it is done making, you should use -
tabHost.setCurrentTab(1);
and you can use same code with different parameters whenever you want to set another tab.
Ref
From the screenshot you must be using Tablayout, so from there you can use these two in build functions.
tabLayout.getSelectedTabPosition();
Save this tab in some variable and then onCreate set that integer value in this function..
tabLayout.getTabAt(<Your last selected tab>);
Hope this helps..:)
You can also use this piece of code:
Add public static TabToOpen = 1 in the group chat activity(say group_chat_activity).
then use setCurrentTab(group_chat_activity.TabToOpen) in onResume() of activity where your ViewPager object is to move to a specific tab. This is particularly useful when you need a button to access a particular tab in sliding activity.

Android how to save the tab state when switching between tabs

I have TabActivity which holds 4 tabs.
the tabs created in the tabhost activity like this
TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
Intent send_names_intent1 = new Intent(this,tab1.class);
//here is some data I receive it from previous activity
//and want to send them to the tab
send_names_intent1.putExtra("names", names);
send_names_intent1.putExtra("check", test1);
firstTabSpec.setIndicator("Kingdom I").setContent(send_names_intent1);
tabHost.addTab(firstTabSpec);
in every tab the user do some work and the result will displayed in the tab,
the problem is that when switching to the 2nd tab and then go back to the 1st tab all the results will gone and the tab will be created again.
NOTICE : I tried to use the getsharedprefrences() but it will loads the saved data even if the application closed and opens again.
You can use a boolean value boolean test; and int value int last=0 then use this method
tabHost.setOnTabChangedListener(new OnTabChangeListener(){
#Override
public void onTabChanged(String tabId) {
int currenttab = tabHost.getCurrentTab();
if (currenttab != last){
test[last] = false;
send_names_intent [last].putExtra("check", test[last]);
last = currenttab;
}
}
});
when you use this method you will have a boolean value in your tab1.class
Intent names_intent = getIntent();
prefcheck = names_intent.getBooleanExtra("check", false);
then check the prefcheck value if (prefcheck == false) save the SharedPreferences.
Have you tried onSaveInstanceState?
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(outState);
icicle.putString("names", names);
}
You say you used shared preferences right? Why not have it so that when a tab is opened, it increments a value of a shared preference by one, and om destroy decrements it, and then checks to see if the value is 0, if so it deletes all the save preferences you want by setting them to the default value, or the value you want.

Android ActionBar tabs set initially selected tab

I have noticed that when using
actionBar.setSelectedNavigationItem(x)
in the onCreate() method of my Activity, the tab item at position 0 is always selected first and then the tab item at position x is loaded. This means that (since I'm using Fragments) 2 Fragments are loaded. One of them being unnecessary...
Here's my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Determine which bundle to use; either the saved instance or a bundle
// that has been passed in through an intent.
Bundle bundle = getIntent().getExtras();
if (bundle == null) {
bundle = savedInstanceState;
}
// Initialize members with bundle or default values.
int position;
if (bundle != null) {
position = bundle.getInt("selected_tab");
} else {
position = 0;
}
// Set the tabs.
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = actionBar
.newTab()
.setText("Tab 1")
.setTabListener(
new TabListener<RendersGridFragment>(this, "1",
RendersGridFragment.class));
actionBar.addTab(tab);
tab = actionBar
.newTab()
.setText("Tab 2")
.setTabListener(
new TabListener<RendersGridFragment>(this, "2",
RendersGridFragment.class));
actionBar.addTab(tab);
tab = actionBar
.newTab()
.setText("Tab 3")
.setTabListener(
new TabListener<RendersGridFragment>(this, "3",
RendersGridFragment.class));
actionBar.addTab(tab);
actionBar.setSelectedNavigationItem(position);
}
It seems that the tab at position 0 is selected initially by default. But, as you can see, I'm passing bundles to make sure the last selected tab is still selected when the activity onCreate() method is run again.
For example,
if the last selected tab is at position 2, the onCreate() runs and the tab at position is 0 is loaded, then the tab at position 2 is loaded.
How can I make sure the ActionBar doesn't select tab at position 0 first when using actionBar.setSelectedNavigationItem(position).
Use the other addTab calls to override this behaviour. You'll need to add the tab you want to be selected first (in your case, the tab at position 2). Relevant Javadoc
actionBar.addTab(tab2);
actionBar.addTab(tab0, 0, false);
actionBar.addTab(tab1, 1, false);
For any others looking to do this you can also set the tab to selected by setting the position and then set true or false to indicate which tab should be selected
actionBar.addTab(tab1, 0, false);
actionBar.addTab(tab2, 1, true);
actionBar.addTab(tab3, 2, false);
Here are the docs on this approach: http://developer.android.com/reference/android/app/ActionBar.html#addTab(android.app.ActionBar.Tab, int, boolean)
you can use below statment in activtiy onStart method:
protected void onStart() {
super.onStart();
actionBar.selectTab(mainTab);
}
which mainTab variable here is of type Tab.
this way you need to define tabs as class-wide variables like this:
Tab mainTab, tab2,tab3;
#Override
protected void onCreate(Bundle savedInstanceState) {
//add tabs to action bar
....
}
If you have 3 tabs (i.e. tab 0, tab 1, tab 2) and want tab 1 to be preselected. Do this:
for (int i = 0; i < mFragmentPagerAdapter.getCount(); i++) {
boolean preselected = (i == 1);
actionBar.addTab(actionBar.newTab().setText(
mFragmentPagerAdapter.getPageTitle(i)).setTabListener(this), preselected);
}
You will be using:
public abstract void addTab (ActionBar.Tab tab, boolean setSelected)
as per this API specification.
bkurzius' answer helped me to fix a problem I was having with the same issue.
What I did was:
private final String TAB_SELECTED = "tab_selected"
...
private int mTabSelected;
...
mTabSelected = savedInstanceState.getInt(TAB_SELECTED);
...
final ActionBar actionbar = getActionBar();
...
actionbar.addTab(tab1, mTabSelected == 0);
actionbar.addTab(tab2, mTabSelected == 1);
actionbar.addTab(tab3, mTabSelected == 2);
...
outState.putInt(TAB_SELECTED, getActionBar().getSelectedNavigationIndex());
This way, the setSelected parameter is true only if mTabSelected is equal to the tab's index.
Percy Vega's reply seems to be the best working solution.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
boolean preselected = (i == ErrorDetails.tab_id);
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this),preselected);
}

How to get tab click in Android?

I have created two tabs in my Activity using the below code. This is working perfectly fine. When I click on the first tab I see its contents and the other one shows its content when clicked on it.
How ever I want to set a variable value to true or false based on the Tab selected. But I dont know how to get the tab click for this tab. Can you please help me on this.
The code :
tabHost.setup();
TabSpec ts = tabHost.newTabSpec("Tab1");
ts.setIndicator("", getResources().getDrawable(R.drawable.tab1_content));
ts.setContent(R.id.tab1Layout);
tabHost.addTab(ts);
TabSpec ts1 = tabHost.newTabSpec("Tab2");
ts1.setIndicator("", getResources().getDrawable(R.drawable.tab2_content));
ts1.setContent(R.id.tab2Layout);
tabHost.addTab(ts1);
Add onTabchangedListener to the tabhost and using selectedTab Value manage whatsoever you want to manage.
selectedTab value will be = 0 for first tab and rest so on
tabHost.setOnTabChangedListener(new OnTabChangeListener(){
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
int selectedTab = tabHost.getCurrentTab() // selected
}
});
Hope it helps :)

Categories

Resources