Reputation: 249
I have a problem when I change from portrait to landscape orientation when programing a gallery. The page position in the method PageAdapter.instantiateItem(View container, int position)
turns 0 when change the screen orientation. I want to store the current page position to keep in this page when the orientation changes.
Upvotes: 1
Views: 1411
Reputation: 3827
You will need to store the currently displayed page in your saved instance state. For how to save state, please read the documentation.
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the current item
savedInstanceState.putInt("current_item", pager.getCurrentItem());
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
After an orientation change, that state can be restored and used to set your pagers position.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentItem = savedInstanceState.getInt("current_item");
}
}
Call pager.setCurrentItem(mCurrentItem);
e.g. in your onStart()
or onResume()
method.
For how to get and set the currently selected item read the ViewPager
documentation:
Upvotes: 2