I created a small Android applications, which use Viewpager for reading a story. Here is my code:
Override the getItem() method of FragmentStatePagerAdapter:
@Override
public Fragment getItem(int position) {
TextStoryChapter chapter = (TextStoryChapter) getIntent().getSerializableExtra("chapter");
return ScreenSlidePageFragment.create(position,chapter);
}
The create() method of ScreenSlidePageFragment
class:
public static final String ARG_PAGE = "page";
private int mPageNumber;
private static String chapterName;
private static String content;
public static ScreenSlidePageFragment create(int pageNumber, TextStoryChapter chapter) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
TextStoryChapterDetail detail = chapter.pages.get(pageNumber);
chapterName = "Page " + Integer.toString(detail.pageNo);
content = detail.content;
fragment.setArguments(args);
return fragment;
}
And the onCreate() method of ScreenSlidePageFragment
class:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
Log.e("PageNumber", Integer.toString(mPageNumber));
}
But when I run the applications, the ViewPager always display the content of page 2 (I created a TextStoryChapter
with 5 content pages) at the start and the same content at the next page. The content of page 1 just disappear. When I navigated to page 3 and slided back to page 1, everything became normal again, no more duplicate content of page 2, and I don't know why and how it happen. Anyone can help me? Thanks a lot!
Take a lock at your code. When ViewPager created, 2 variables chapterName
and chapterContent
data will be re-assign and your page 1 data will be lost. You should post your data into a Bundle
, this will help.