jeudi 30 juin 2016

savedInstanceState is always null, yet onSaveInstanceState() is always called

First of all I'm new to Android - this question could seem stupid :)

I've created an main Activity that contains a ViewPager. The ViewPager is linked to my ActionBar tabs. Currently my main Activity contains 3 tabs in this way.

My issue is the following: when I'm on the 3rd tab and create a new Activity and afterwards return to my main Activity I always return to my 1st tab.

I've tried the following approach in my main Activity:

// debugger breakpoints tell me this method is always called when other activity is shown ...
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    int pos = getActionBar().getSelectedNavigationIndex();
    outState.putInt("tab", pos);
}

// however, in onCreate() my savedInstanceState is always 'null' ...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.invalidateOptionsMenu();

    setContentView(R.layout.activity_main);

    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    mViewPager
            .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    actionBar.setSelectedNavigationItem(position);
                }
            });

    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        actionBar.addTab(actionBar.newTab()
                .setText(mSectionsPagerAdapter.getPageTitle(i))
                .setTabListener(this));
    }

    // trying to restore state here, yet savedInstanceState is _always_ null ...
    if (savedInstanceState != null) {
        actionBar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
    }
}

I've read that the savedInstanceState will always be null when there's no id defined. My XML layout has an id defined though, so this should not be an issue. I've also read that the 'onSaveInstanceState()` method should always call the method on the super class first, so I've implemented the method accordingly.

Anyone have any idea how to fix my issue? How to get the ViewPager to show the right tab / fragment when the main Activity is recreated?

Aucun commentaire:

Enregistrer un commentaire