PagerAdapter start position
I have noticed that if you recreate Activity (orientation change) with ViewPager having FragmentStatePagerAdapter, then the Adapter will reuse it's Fragments. The way to stop it is:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
if (viewPager != null) {
// before screen rotation it's better to detach pagerAdapter from the ViewPager, so
// pagerAdapter can remove all old fragments, so they're not reused after rotation.
viewPager.setAdapter(null);
}
super.onSaveInstanceState(savedInstanceState);
}
but then after Activity recreation ViewPager alwayes opens page 0 first and setCurrentItem(CurrentPosition); doesn't work. Fix for that is changing page after delay:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
viewPager.setCurrentItem(newPosition);
}
}, 100);
I came across a problem whereby if I set the current item before I set the adapter, the first item I get back will always be the one at position 0.
Make sure you do:
awesomePager.setAdapter(awesomeAdapter);
awesomePager.setCurrentItem(CurrentPosition);
and not:
awesomePager.setCurrentItem(CurrentPosition);
awesomePager.setAdapter(awesomeAdapter);
I've found a way to set it's position, which is done outside of the class:
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
awesomePager.setAdapter(awesomeAdapter);
awesomePager.setCurrentItem(CurrentPosition);
and it can be limited by calculating the amount of items I want to fit in to it
To start with the last fragment I did this:
PagerAdapter pagerAdapter = new PagerAdapter();
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(pagerAdapter.getCount() - 1);