方向更改后保持当前选项卡Actionbar Android

时间:2012-11-21 10:59:41

标签: android android-actionbar

在我的应用程序中,当方向更改时,操作栏中的选定选项卡设置为第一个,我希望它保留在选定的选项卡上,而不是跳到第一个选项卡...

3 个答案:

答案 0 :(得分:25)

使用onSavedInstanceState可以非常轻松地执行此操作:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    int i = getActionBar().getSelectedNavigationIndex();
    outState.putInt("index", i);
}

然后在你的onCreate()方法中包含它:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
            ...
    if(savedInstanceState != null) {
        int index = savedInstanceState.getInt("index");
        getActionBar().setSelectedNavigationItem(index);
    }
}

答案 1 :(得分:0)

21+ with toolbar对我有用:

import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity {



   private ViewPager viewPager;
   private static final String FLAG_CURRENTLY_SELECTED_TAB_INDEX = "currentlySelectedTabIndex";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mylayout);


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeAsUpIndicator(R.mipmap.ic_launcher);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        FragmentManager fragmentManager = getSupportFragmentManager(); 
        viewPager.setAdapter(getMyCustomAdapter());            

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);     

        if (savedInstanceState != null) {
            final int currentlySelectedTabIndex = savedInstanceState.getInt(FLAG_CURRENTLY_SELECTED_TAB_INDEX, -1);
            if (currentlySelectedTabIndex > -1) {
                viewPager.setCurrentItem(currentlySelectedTabIndex);
            }
        }

    }

 @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState); 

        if (viewPager != null) {
            int i = viewPager.getCurrentItem();
            outState.putInt(FLAG_CURRENTLY_SELECTED_TAB_INDEX, i);
        }
    }

答案 2 :(得分:-1)

由于getLastNonConfigurationInstance()已被弃用,因此在FragmentActivity中只需覆盖onRetainCustomNonConfigurationInstance()并使用新的getLastCustomNonConfigurationInstance()

@Override
public Object onRetainCustomNonConfigurationInstance() {
    return mViewPager.getCurrentItem();
}

并在onCreate()中检索它,如下所示:

Integer lastTab = (Integer) getLastCustomNonConfigurationInstance();
if (lastTab != null) {
    mViewPager.setCurrentItem(lastTab);
}