Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch tabs programmatically in Android from fragment?

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); } 
like image 601
vinothp Avatar asked May 01 '13 08:05

vinothp


People also ask

How to create TabLayout with ViewPager2?

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.

How to create swipe screen in Android studio?

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 .


1 Answers

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.

like image 133
Kennedy Nyaga Avatar answered Sep 20 '22 06:09

Kennedy Nyaga