5

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

4

3 回答 3

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);
    }
}
于 2013-04-26T11:22:50.657 回答
0

对于带有工具栏的 21+,这对我有用:

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);
        }
    }
于 2015-06-18T14:13:32.873 回答
-1

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

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

并像这样检索它onCreate()

Integer lastTab = (Integer) getLastCustomNonConfigurationInstance();
if (lastTab != null) {
    mViewPager.setCurrentItem(lastTab);
}
于 2013-02-28T19:35:59.870 回答