如何在viewpager中切换片段?

时间:2014-03-07 16:13:33

标签: android android-viewpager

我有一个包含3个片段的ViewPager:

    VP = new SettingsScrollViewPager( this );
    VP.setScrollDurationFactor( 4 );
    VP.setId( "ST".hashCode() );
    setContentView( VP );

    // add fragments
    ArrayList<Fragment> fragmentsContainer = appHelper.addFragments( 
        new SettingsFragment(),
        new SearchFragment(),
        new FavoritesFragment()
    );

    VP.setAdapter( new SettingsFPA( getSupportFragmentManager(), fragmentsContainer ) );
    VP.setOffscreenPageLimit( 1 );
    VP.setCurrentItem( 0 );

我想在单击按钮后用SearchFragment替换FavoritesFragment,但是我该怎么做?它应该是这样的:

    ArrayList<Fragment> fragmentsContainer = appHelper.addFragments( 
        new SettingsFragment(),
        new FavoritesFragment(),
        new SearchFragment()
    );

这是我的适配器的样子:

public class SettingsFPA extends FragmentPagerAdapter {

private static ArrayList<Fragment> mFragments;

public SettingsFPA( FragmentManager manager, ArrayList<Fragment> container ) { 
    super(manager);
    mFragments = container;
}

@Override
public int getCount() {
    return mFragments.size();
}

@Override
public Fragment getItem(int position) {
    return mFragments.get(position);
}

}

我应该将Index 1与Index 2交换,这就是我想要实现的目标,所以任何帮助都将受到赞赏!

1 个答案:

答案 0 :(得分:1)

让我知道这是否有效:

在SettingsFPA类

中创建方法
public void swapFragments() {
    Collections.swap(mFragments, 1, 2);
    notifyDataSetChanged();
}

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}

点击按钮上的活动调用swapFragments:

mSettinfsFPAAdapter.swapFragments();