当您想使用 ViewPager 解决问题时,您需要在 onCreate 方法中使用它:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = (ViewPager) findViewById(R.id.pager);
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
// Capture ViewPager page swipes
ViewPager.SimpleOnPageChangeListener ViewPagerListener = new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
if (fistswitch) {
mPager.setCurrentItem(1);
fistswitch = false;
} else {
// here you can use the replace method, to switch the
// fragment behind the scenes
ArrayList<Fragment> fragmentList = new ArrayList<Fragment>();
Collections.addAll(fragmentList, new Fr2(), new Fr3(), new Fr4());
mPagerAdapter.addFragments(fragmentList);
// after the first switch you can use the the second page
// continuously as middle
mPager.setCurrentItem(1);
}
}
};
mPager.setOnPageChangeListener(ViewPagerListener);
mPagerAdapter = new ViewPagerAdapter(fm);
mPager.setAdapter(mPagerAdapter);
ArrayList<Fragment> fragmentList = new ArrayList<Fragment>();
Collections.addAll(fragmentList, new Fr1(), new Fr2(), new Fr3());
mPagerAdapter.addFragments(fragmentList);
}
寻呼机适配器类可以是您活动中的私有类,如下所示:
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragmentList = new ArrayList<Fragment>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragments(List<Fragment> fragments) {
fragmentList.clear();
fragmentList.addAll(fragments);
notifyDataSetChanged();
}
public void replaceFragment(int position, Fragment fr) {
fragmentList.remove(position);
fragmentList.add(position, fr);
notifyDataSetChanged();
}
@Override
public int getItemPosition(Object object) {
if (fragmentList.contains(object)) {
return POSITION_UNCHANGED;
}
return POSITION_NONE;
}
@Override
public Fragment getItem(int item) {
if (item >= fragmentList.size()) {
return null;
}
return fragmentList.get(item);
}
@Override
public int getCount() {
return fragmentList.size();
}
}
我没有测试过代码,但它在类似的情况下对我有用。