按下后退按钮时保存tabLayout位置

时间:2016-03-25 06:14:18

标签: android

当用户按下“返回”按钮时,如何保存并返回标签位置?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    ViewPager vpPager = (ViewPager) findViewById(R.id.viewpager);
    adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
    vpPager.setAdapter(adapterViewPager);

    // Give the TabLayout the ViewPager
    tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setTabMode(TabLayout.MODE_FIXED);
    tabLayout.setupWithViewPager(vpPager);

    // Attach the page change listener inside the activity
    vpPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(POSITION, tabLayout.getSelectedTabPosition());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    viewPager.setCurrentItem(savedInstanceState.getInt(POSITION));
}

我是否使用onBackPressed()来执行此操作? 非常感谢帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式进行背压操作:

@Override
public void onBackPressed() {
  int pos =  mViewPager.getCurrentItem();
}

当你回到屏幕时,你可以设置寻呼机的位置

@Override
public void onResume(){
super.onResume();
// put your code here...

if(mViewPager !=null)

 mViewPager.setCurrentItem(pos); 

}