How to switch tabs programmatically in Android from fragment?

风流意气都作罢 提交于 2019-11-30 04:54:53

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.

Finally i can switch between the tabs programatically from Fragments using the following line of code

  TabHost host = (TabHost) getActivity().findViewById(android.R.id.tabhost);
  host.setCurrentTab(2);

Hope it will help some one.

I have tabs (using TabLayout not TabHost(depreciated))(with Fragments) in my Main Activity in which in my first tab(fragment) with a click listener in the fragment which is for changing the current tab in my MainActivity.

I successfully change the current tab via the below in the onCreateView() method within the fragment.

TabLayout tabs = (TabLayout)((MainActivity)getActivity()).findViewById(R.id.tabs);
tabs.getTabAt(1).select();
TomTasche

Take a look at this answer: https://stackoverflow.com/a/5460651/198996

((TabActivity) getParent()).getTabHost().setCurrentTab(2)

If you're using TabLayout instead of TabHost , I suggest a modification to BENN1TH's answer that worked for me:

  TabLayout tabs = getActivity().findViewById(R.id.tab_layout);
  tabs.getTabAt(tabNumber).select(); 

(The difference is R.id.tab_layout)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!