Retrieve a Fragment from a ViewPager

前端 未结 23 2520
逝去的感伤
逝去的感伤 2020-11-21 11:13

I\'m using a ViewPager together with a FragmentStatePagerAdapter to host three different fragments:

  • [Fragment1]
  • [Fragment2]<
23条回答
  •  孤街浪徒
    2020-11-21 11:59

    I handled it by first making a list of all the fragments (List fragments;) 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.

提交回复
热议问题