Configuration changed (orientation change) and destroying Activities - is this the way it's supposed to work?

前端 未结 4 662
轻奢々
轻奢々 2020-12-31 04:00

I read up on how Android handles \"configuration changes\" - by destroying the active Activity.

I really want to know from Android Team why this is. I would apprecia

相关标签:
4条回答
  • 2020-12-31 04:33

    The contents of an EditText will be saved for you automatically when rotating the screen if you put an android:id attribute on it. Similarly, if you display dialogs using Activity#showDialog, then the dialogs are reshown for you after rotating.

    0 讨论(0)
  • 2020-12-31 04:45

    @Alex's approach above pointed me to a really, really useful solution when using fragments:

    Fragments usually get recreated on configuration change. If you don't wish this to happen, use

    setRetainInstance(true); in the Fragment's constructor(s)

    This will cause fragments to be retained during configuration change.

    http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)

    0 讨论(0)
  • 2020-12-31 04:49

    on why part - short answer - because you might have resources that needed to be changed as you've rotated the phone. ( Images, layout might be different, etc )

    On save - you can save you stuff to bundle and read it back.

      @Override
        protected void onSaveInstanceState(Bundle outState) {
    
                String story_id = "123"
                outState.putString(ContentUtils.STORYID, story_id);
    
        }
    

    or you can use onRetainNonConfigurationInstance () as described here http://developer.android.com/reference/android/app/Activity.html#onRetainNonConfigurationInstance()

    Finally if you don't have anything you want to handle during rotation - you can ignore it by putting this into your activity in manifest

    android:configChanges="keyboardHidden|orientation"
    

    In general, i would read trough article from url above couple of times, until lifecycle is crystal clear.

    0 讨论(0)
  • 2020-12-31 04:50

    You should read the Application Fundamentals (specifically, Activity lifecycle). Since Activitys must be able to handle being killed at any time due to memory contraints, etc. it's just a cleaner way to handle rotations without adding too much complexity - instead of checking every resource for an alternate resource, re-structuring the layout, etc. you just save your essential data, kill the activity, re-create it, and load the data back in (if you're willing to deal with the extra complexity of managing this yourself, you can use onConfigurationChanged to handle the configuration change yourself.) This also encourages better practices - developers have to be prepared for their Activity to be killed for orientation change, which has the (good) consequence of being prepared for being killed off by memory contraints also.

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