Reputation: 43
I'm using ViewPager and TabLayout to display a fragment which can be easily switched by selecting tabs. I have 5 tabs with Fragment one, two, three, four and five.
In fragment one I have a Button. How do I switch to other tabs, for example tab 4, by clicking that button instead of tabs.
Here is the Mainactivity
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Home(), "Home");
adapter.addFragment(new speed(), "Quick Dial");
adapter.addFragment(new hospital(), "Hospital");
adapter.addFragment(new ambulance(), "Ambulance");
adapter.addFragment(new funeral(), "Funeral");
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
and fragment one contains
@Override
public void onClick(View v) {
switch (getAdapterPosition()) {
case 0:
//Switch to tab position two
case 1:
//Switch to tab position three
case 2:
//Switch to tab position four
}
}
}
}
Thanks in advance.
Upvotes: 0
Views: 118
Reputation: 549
You can register a BroadcastReciever
in your activity and send a brodcast from your first fragment to the activity as soon as the button is clicked.
Inside BroadcastReciever
change the ViewPager
index,
viewPager.setCurrentItem(index);
Additionally You can also send the index to be switched to, by passing data through intent.
Upvotes: 0
Reputation: 468
You can write in code in onClick(View v)
viewPager.setCurrentItem(index);
Index is the fragment number which you want to show. Try this. I hope your problem will be solved.
Upvotes: 2