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

后端 未结 8 1448
甜味超标
甜味超标 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:49

    public class MyActivity extends Activity {
        boolean fromOrientation=false;
        SharedPreferences myPrefLogin;
        Editor prefsEditor;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            prefsEditor = myPrefLogin.edit();
            myPrefLogin = this.getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);
            fromOrientation = myPrefLogin.getString("fromOrient", false);
    
            if(fromOrientation) {
                 // do as per need--- logic of orientation changed.
            } else {
                 // do as per need--- logic of default onCreate().
            }
        }
    
        @Override
        public Object onRetainNonConfigurationInstance() {
            prefsEditor.putString("fromOrient", true);
            prefsEditor.commit();
            return null;
        }
    
        @Override
        protected void onDestroy() {
            if(fromOrientation) {
                prefsEditor.putString("fromOrient", false);
                prefsEditor.commit();
            }
            super.onDestroy();
        }  
    }
    

    flag fromOrientation(tells the state either configuration had been change or not) above we had done like by defalut we are considering that onCreate() is not called from by changing orientation. If orientation changed(onRetainNonConfigurationInstance()) then we set the flag value in preference which let us know whether onCreate() is called from on orientation or not. And finally onDestroy() we again reset the orientation flag.

提交回复
热议问题