How to switch tabs programmatically in Android from fragment?

vinothp picture vinothp · May 1, 2013 · Viewed 33.8k times · Source

I have implemented a TabActivity which extends FragmentActivity. It has 5 tabs each tab is a Fragment. What i am looking for is to switch between the tabs programmatically.

For eg: if i am in tab4. On button click I want to move from tab4 to tab1. Tried a lot but couldn't find the solution for this.

Tried with the following but it doesn't help.

From SecondTab

public void switchTabInActivity(String value){
    FirstTab parent;
    parent = (FirstTab) getActivity().getParent();
    parent.switchTab(value);
}

TabActivity

  /** To Change Tab*/
public void switchTab(String tabno){ 
    this.onTabChanged(tabno);
}

Answer

Kennedy Nyaga picture Kennedy Nyaga · Aug 24, 2015

for Material support you switch the tablayout from a fragment in the following ways:

1) send a broadcast that is received by the parent activity which then modifies the tab.

context.sendBroadcast(yourintent);

2.) A modification of vino's answer,

TabLayout tabhost = (TabLayout) getActivity().findViewById(R.id.tabLayout);
tabhost.getTabAt(2).select();

tablayout is the id of the tablayout as defined in your main xml.