简体   繁体   中英

FragmentPagerAdapter showing fragments wrongly in ViewPager

I have an ActionBarActivity inside which I have a ViewPager . I expect to see four (first, second, third, four) fragments in four (first, second, third, fourth) pages.

Problem:

  • I see the second fragment on the first page.
  • I then move to the second page. Saw nothing.
  • I then move back to the first page. Saw the second fragment.

In the onCreate() of the ActionBarActvity , I have:

mViewPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), mGoodArrayListOfWords); 
mViewPager.setAdapter(mPagerAdapter);

This is how MyPagerAdapter looks:

public class MyPagerAdapter extends FragmentPagerAdapter {

    private ArrayList<String> mWords;


    public MyPagerAdapter(FragmentManager fm, ArrayList<String> words) {
        super(fm);
        mWords = words;
    }


    @Override
    public Fragment getItem(int position) {
        String specificWord = mWords.get(position);
        return MyFragment.newInstance(specificWord);
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return mWords.get(position);
    }
}

I instantiated a MyFragment using a static factory method and I made the no-arg constructor private:

    public static MyFragment newInstance(String word) {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.putString("WORD", word);
        fragment.setArguments(args);
        return fragment;
    }

    private MyFragment() {
        super();
    }

Moreover, in onViewOnCreated() , I get a handle to the fragment's list view, use the LoaderManager to init() a loader. I update the list view's adapter in onLoadFinished() of the LoaderManager.LoaderCallbacks<Cursor> .

I think the problem is due to the Loader s finish their jobs after the fragments' views have been created. Log when I expect two pages and two fragments:

04-01 23:15:55.707 D/DebugTag﹕ getItem called
04-01 23:15:55.717 D/DebugTag﹕ getItem called
04-01 23:15:55.717 D/DebugTag﹕ on view created called
04-01 23:15:55.797 D/DebugTag﹕ on view created called
04-01 23:15:56.157 D/DebugTag﹕ on load finished called
04-01 23:15:56.177 D/DebugTag﹕ on load finished called

Extend FragmentStatePagerAdapter as you're using getItem() method. If you want to keep it FragmentPagerAdapter override instantiateItem() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM