FragmentPagerAdapter永远不会被getItem()调用

时间:2017-01-28 18:24:30

标签: android android-viewpager android-adapter

我花了2个小时试图解决问题。代码在昨天工作,但是当我今天试图运行ViewPager时,它就不会显示碎片。调试后,我注意到getcount()内的FragmentPagerAdapter被调用,但我的getItem()永远不会。谁能告诉我我的代码有什么问题?

我的ViewPagerFragment课程:

public class ViewPagerFragment extends Fragment {


public static final String ARGS_KEY="schedules";


 ViewPager mViewPager;
ArrayList<Schedule> mSchedules;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view=inflater.inflate(R.layout.fragment_view_pager,container,false);
    ButterKnife.bind(this,view);

    mViewPager= (ViewPager) view.findViewById(R.id.viewPager);
    mSchedules= Parcels.unwrap(getArguments().getParcelable(ARGS_KEY));

    final ArrayList<Fragment> fragments=setupFragments(mSchedules);
    ViewPagerAdapter viewPagerAdapter=ViewPagerAdapter.initializeWithFragmentList(fragments,getChildFragmentManager());

    mViewPager.setAdapter(viewPagerAdapter);

    return view;
}


private ArrayList<Fragment> setupFragments(ArrayList<Schedule> Schedules ){
    ArrayList<Fragment> fragments=new ArrayList<>();

    for (Schedule schedule:Schedules){
        ViewPagerItemFragment fragment= createViewPagerItem(schedule);
        fragments.add(fragment);
    }

    return fragments;
}

public  ViewPagerItemFragment createViewPagerItem(Schedule schedule){
    Checker.checkIfObjectNull(schedule);
    ViewPagerItemFragment viewPagerItemFragment=new ViewPagerItemFragment();
    setArgsForFragment(viewPagerItemFragment,schedule);

    return viewPagerItemFragment;
}

private ViewPagerItemFragment setArgsForFragment(ViewPagerItemFragment fragment,Schedule schedule){
    Bundle args=new Bundle();
    args.putParcelable(ViewPagerItemFragment.ARGS_KEY,Parcels.wrap(schedule));
    fragment.setArguments(args);

    return fragment;
}

我的ViewPagerAdapter班级:

public class ViewPagerAdapter extends FragmentPagerAdapter {

ArrayList<Fragment> mFragments;


public static ViewPagerAdapter initializeWithFragmentList(ArrayList<Fragment> fragments, FragmentManager fragmentManager){
    return new ViewPagerAdapter(fragmentManager,fragments);
}

private ViewPagerAdapter(FragmentManager fm,ArrayList<Fragment> fragments) {
    super(fm);
    mFragments=fragments;
}


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

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

}

1 个答案:

答案 0 :(得分:0)

好的,我发现了问题。真的很傻。我使用genymotion模拟器,由于某种原因它没有正确调试我的代码。重述模拟器似乎解决了这个问题。