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); }
Open the MainActivity class. Firstly, initialize ViewPager2 and TabLayout then set the adapter on ViewPager2. Then, create a TabLayoutMediator to link the TabLayout to the ViewPager2, and attach it.
You can create swipe views using AndroidX's ViewPager widget. To use ViewPager and tabs, you need to add a dependency on ViewPager and on Material Components to your project. To insert child views that represent each page, you need to hook this layout to a PagerAdapter .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With