我在纵向模式下有一个视图寻呼机。在横向模式下,我有完全不同的布局。从风景回到肖像后,我想看看最后看到的viewpager页面。但总是第一页在屏幕上。
以下是我的代码:
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"));
}
}
}
答案 0 :(得分:3)
我目前没有打开IDE,因此可能需要进行语法更正:
@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));
}
}