我正在尝试在视图寻呼机的页面更改上添加片段。但是每次当我滚动视图寻呼机时,都会创建新的片段瞬间。
public void initializeViewPager(int currentPage, String selectedCardNumber) {
currentPosition = currentPage;
FragmentPagerAdapter journeyViewPagerAdapter =
new ViewPagerAdapter(getSupportFragmentManager());
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Default Implementation
}
@Override
public void onPageSelected(int position) {
currentPosition = position;
addFragments(position, selectedCardNumber);
handleScrollState();
}
@Override
public void onPageScrollStateChanged(int state) {
//Default Implementation
}
};
viewPager.addOnPageChangeListener(onPageChangeListener);
initCarousalAdapter();
}
addFragments() 方法
private void addFragments(int position, final String selectedCardNumber) {
FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
bundle.putInt(ApplicationConstants.SELECTED__TYPE, position);
bundle.putString(DataConstants.SELECTED__NUMBER, selectedCardNumber);
switch (position) {
case 1:
OffersFragmentOne fragment = OffersFragmentOne.getInstance();
fragment.setArguments(bundle);
fragTransaction.replace(R.id.btmt_fragment_container, fragment);
break;
case 2:
OffersFragmentTwo mtFragment = OffersFragmentTwo.getInstance();
mtFragment.setArguments(bundle);
fragTransaction.replace(R.id.btmt_fragment_container, mtFragment);
break;
case 3:
OffersFragmentThree poFragment = OffersFragmentThree.getInstance();
poFragment.setArguments(bundle);
fragTransaction.replace(R.id.btmt_fragment_container, poFragment);
break;
default:
//Default Implementation
}
fragTransaction.commit();
}
getInstance() 方法
private static OffersFragmentOne offersFragmentOne;
public static OffersFragmentOne getInstance() {
if (OffersFragmentOne == null) {
offersFragmentOne = new OffersFragmentOne();
}
return offersFragmentOne;
}
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final int[] carousalImages = {R.drawable.ic_po_carousal_banner,
R.drawable.ic_bt_carousal_banner,
R.drawable.ic_mt_carousal_banner, R.drawable.ic_po_carousal_banner,
R.drawable.ic_bt_carousal_banner};
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
@Override
public Fragment getItem(int position) {
CarousalFragment frag = new CarousalFragment();
CarousalFragmentPresenter.createAndAttach(frag, carousalImages[position]);
return frag;
}
@Override
public int getCount() {
return carousalImages != null ? carousalImages.length : 0;
}
}