Activity restart on rotation Android

前端 未结 30 3913
花落未央
花落未央 2020-11-21 04:32

In my Android application, when I rotate the device (slide out the keyboard) then my Activity is restarted (onCreate is called). Now, this is proba

30条回答
  •  时光说笑
    2020-11-21 04:58

    There are several ways to do this:

    Save Activity State

    You can save the activity state in onSaveInstanceState.

    @Override
    public void onSaveInstanceState(Bundle outState) {
        /*Save your data to be restored here
        Example : outState.putLong("time_state", time); , time is a long variable*/
        super.onSaveInstanceState(outState);
    }
    

    and then use the bundle to restore the state.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        if(savedInstanceState!= null){
           /*When rotation occurs
            Example : time = savedInstanceState.getLong("time_state", 0); */
        } else {
          //When onCreate is called for the first time
        }
    }
    

    Handle orientation changes by yourself

    Another alternative is to handle the orientation changes by yourself. But this is not considered a good practice.

    Add this to your manifest file.

    android:configChanges="keyboardHidden|orientation"
    

    for Android 3.2 and later:

    android:configChanges="keyboardHidden|orientation|screenSize"
    
    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
    
    if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            //Handle rotation from landscape to portarit mode here
        } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
            //Handle rotation from portrait to landscape mode here
        }
    }
    

    Restrict rotation

    You can also confine your activity to portrait or landscape mode to avoid rotation.

    Add this to the activity tag in your manifest file:

            android:screenOrientation="portrait"
    

    Or implement this programmatically in your activity:

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    

提交回复
热议问题