I\'m using a ViewPager
together with a FragmentStatePagerAdapter
to host three different fragments:
I handled it by first making a list of all the fragments (List
) that I was going to use then added them to the pager making it easier to handle the currently viewed fragment.
So:
@Override
onCreate(){
//initialise the list of fragments
fragments = new Vector();
//fill up the list with out fragments
fragments.add(Fragment.instantiate(this, MainFragment.class.getName()));
fragments.add(Fragment.instantiate(this, MenuFragment.class.getName()));
fragments.add(Fragment.instantiate(this, StoresFragment.class.getName()));
fragments.add(Fragment.instantiate(this, AboutFragment.class.getName()));
fragments.add(Fragment.instantiate(this, ContactFragment.class.getName()));
//Set up the pager
pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragments));
pager.setOffscreenPageLimit(4);
}
so then this can be called:
public Fragment getFragment(ViewPager pager){
Fragment theFragment = fragments.get(pager.getCurrentItem());
return theFragment;
}
so then i could chuck it in an if statement that would only run if it was on the correct fragment
Fragment tempFragment = getFragment();
if(tempFragment == MyFragmentNo2.class){
MyFragmentNo2 theFrag = (MyFragmentNo2) tempFragment;
//then you can do whatever with the fragment
theFrag.costomFunction();
}
but thats just my hack and slash approach but it worked for me, I use it do do relevent changes to my currently displayed fragment when the back button is pushed.