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

前端 未结 3 2041
佛祖请我去吃肉
佛祖请我去吃肉 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);
        }
    }
    

提交回复
热议问题