MSr MSr - 3 months ago 11
Android Question

Saving current page of view pager

I have a view pager on portrait mode. On landscape mode I have completely different layout. After coming back to portrait from landscape, I want to see last seen page of viewpager. But always first page is on the screen.

Here are my codes:

public class MainActivity extends FragmentActivity {

public static ViewPager pager=null;
public static FragmentAdapter adapter;
PageIndicator mIndicator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delict);
if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_PORTRAIT){
pager = (ViewPager) findViewById(R.id.pager);
adapter = new FragmentAdapter(getSupportFragmentManager());
pager.setOffscreenPageLimit(4);
pager.setAdapter(adapter);
mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(pager);
mIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
Toast.makeText(MainActivity.this, "Changed to page " + position, Toast.LENGTH_SHORT).show();
}

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}

@Override
public void onPageScrollStateChanged(int state) {
}
});
}

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.delict, menu);
return true;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_PORTRAIT){
if(pager!=null){
outState.putInt("PAGE", pager.getCurrentItem());
}
}

}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if(pager!=null){
pager.setCurrentItem(savedInstanceState.getInt("PAGE"));
}
}
}

Answer

I do not have my IDE open at the moment, so syntax corrections might be needed:

@Override
protected void onSaveInstanceState(Bundle bundle) {
  super.onSaveInstanceState(bundle);
  bundle.putInt("currentItem", pager.getCurrentItem());
}

public void onCreate(Bundle savedInstanceState) {

    ...

    if (savedInstanceState != null) {
        pager.setCurrentItem(savedInstanceState.getInt("currentItem", 0));
    }
}
Comments