Albert078
Albert078

Reputation: 363

Switch fragments programmatically

I have a pager with two fragments, each with its own xml. My question is whether it is possible to switch from one fragment to another programmatically and to fire on any listener?

Best Regards

Upvotes: 10

Views: 9134

Answers (3)

Camilo Ortegón
Camilo Ortegón

Reputation: 3692

You need to set current item in ViewPager and then you should notify the adapter to make it bring the new Fragment.

ViewPager ViewPager;
FragmentPagerAdapter adapter;

pager.setCurrentItem(2);
adapter.notifyDataSetChanged();

Upvotes: 3

gcl1
gcl1

Reputation: 4120

If you are using ViewPager, you can try setSelectedNavigationItem(). That is, you can switch from one fragment to another by calling:

int position = 0;  // position of the tab you want
((ParentActivity) getActivity()).getActionBar().setSelectedNavigationItem(position);

or, if you're using ActionBarSherlock:

int position = 0;  // position of the tab you want
((ParentActivity) getActivity()).getSupportActionBar().setSelectedNavigationItem(position);

Upvotes: 0

sgarman
sgarman

Reputation: 6182

I'm assuming you mean ViewPager. You can toggle between them by using pager.setCurrentItem(index)

Upvotes: 11

Related Questions