Retrieve a Fragment from a ViewPager

前端 未结 23 2575
逝去的感伤
逝去的感伤 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:37

    Ok for the adapter FragmentStatePagerAdapter I fund a solution :

    in your FragmentActivity :

    ActionBar mActionBar = getSupportActionBar(); 
    mActionBar.addTab(mActionBar.newTab().setText("TAB1").setTabListener(this).setTag(Fragment.instantiate(this, MyFragment1.class.getName())));
    mActionBar.addTab(mActionBar.newTab().setText("TAB2").setTabListener(this).setTag(Fragment.instantiate(this, MyFragment2.class.getName())));
    mActionBar.addTab(mActionBar.newTab().setText("TAB3").setTabListener(this).setTag(Fragment.instantiate(this, MyFragment3.class.getName())));
    
    viewPager = (STViewPager) super.findViewById(R.id.viewpager);
    mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), mActionBar);
    viewPager.setAdapter(this.mPagerAdapter);
    

    and create a methode in your class FragmentActivity - So that method give you access to your Fragment, you just need to give it the position of the fragment you want:

    public Fragment getActiveFragment(int position) {
    String name = MyPagerAdapter.makeFragmentName(position);
    return getSupportFragmentManager().findFragmentByTag(name);
    }
    

    in your Adapter :

    public class MyPagerAdapter extends FragmentStatePagerAdapter {
    
    private final ActionBar actionBar;
    private final FragmentManager fragmentManager;
    
    public MyPagerAdapter(FragmentManager fragmentManager, com.actionbarsherlock.app.ActionBarActionBar mActionBar) {super(fragmentManager);
    this.actionBar = mActionBar;
    this.fragmentManager = fragmentManager;
    }
    
    @Override
    public Fragment getItem(int position) {
    getSupportFragmentManager().beginTransaction().add(mTchatDetailsFragment, makeFragmentName(position)).commit();
    return (Fragment)this.actionBar.getTabAt(position);
    }
    
    @Override
    public int getCount() {
    return this.actionBar.getTabCount();
    }
    
    @Override
    public CharSequence getPageTitle(int position) {
    return this.actionBar.getTabAt(position).getText();
    }
    
    private static String makeFragmentName(int viewId, int index) {
    return "android:fragment:" + index;
    }
    
    }
    

提交回复
热议问题