Is that possible to check was onCreate called because of orientation change?

后端 未结 8 1485
甜味超标
甜味超标 2020-12-06 00:08

I need to act differently in onStart() method depending on how onCreate() was called in result of orientation change or not. Is that

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-06 00:51

    As others have said, save the state:

    public class MyActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            if(savedInstanceState == null) {
                // app started afresh, don't check orientation
                /* do application first-run stuff */
            } else {
                // re-started, so check for orientation change
                boolean orientationChanged = false;
                if(savedInstanceState != null) {
                    int lastOrientation = savedInstanceState.getInt("last_orientation");
                    orientationChanged = (getOrientation() != lastOrientation);
                }
    
                if(orientationChanged) {
                    // orientation changed
                    /* do stuff */
                } else {
                    // orientation has not changed
                    /* do stuff */
                }
            }
        }
    
        @Override
        public void onSaveInstanceState(Bundle savedInstanceState) {
            super.onSaveInstanceState(savedInstanceState);
            savedInstanceState.putInt("last_orientation", getOrientation());
        }
    
        private int getOrientation() {
            // ...
        }
    }
    

提交回复
热议问题