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

前端 未结 3 2042
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-04 02:53

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

相关标签:
3条回答
  • 2021-01-04 03:11

    Thanks She Smile, your suggestions helped me solve my issue, because it helped me find the source of my problem.

    Apparently onCreate() could only have a savedInstanceState parameter when the Activity was completely destroyed and recreated. In my case the Activity still existed though, therefore I will not have a savedInstanceState parameter. My "fix" was to create a static int that contains the selected tab index. I realise this might not be the best solution, since this variable will be shared across all instances of the Activity, but since in my situation there will only even be one instance of my activity it should be fine.

    public class MainActivity extends Activity implements ActionBar.TabListener {
        private static int tabIdx;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            if (savedInstanceState != null) {
                tabIdx = savedInstanceState.getInt("tab", 0);
            }
            getActionBar().setSelectedNavigationItem(tabIdx);
        }
    
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
    
            tabIdx = getActionBar().getSelectedNavigationIndex();
            outState.putInt("tab", tabIdx);
        }
    }
    
    0 讨论(0)
  • 2021-01-04 03:22

    so if the onSaveInstance was Called

    you can declare a global variable for your

     int pos=0; 
    

    after onSaveInstance() gets called, method below is called:

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    pos=savedInstanceState.getInt("tab", 0);    
    

    }

    so in your onCreate() function replace the condition from this:

    if (savedInstanceState != null) {
        actionBar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
    }
    

    to this:

    if(pos>0){
    actionBar.setSelectedNavigationItem(pos);
    }
    
    0 讨论(0)
  • 2021-01-04 03:34

    The onRestoreInstanceState() method is only called when there is a Bundle object to restore from, i.e. it is NOT NULL. Otherwise, the restore method will not be called.

    0 讨论(0)
提交回复
热议问题