Search code examples
androidlayoutandroid-orientation

android prevent refresh on change orientation


I have layout/activity_main.xml and layout-land/activity_main.xml. When I change orientation the activity reload again.

I try to use this code android:configChanges="keyboardHidden|orientation" and it work the activity is not reloading just what i like but the problem is the layout is not switching from layout/activity_main.xml to layout-land/activity_main.xml.

How do i switch from layout/activity_main.xml to layout-land/activity_main.xml. without refreshing the activity.


Solution

  • By declaring android:configChanges="orientation|screenSize" you instruct Activity Manager to not restart your activity and let you handle configuration change via onConfigurationChanged().

    If your application doesn't need to update resources during a specific configuration change and you have a performance limitation that requires you to avoid the activity restart, then you can declare that your activity handles the configuration change itself, which prevents the system from restarting your activity.

    Source: http://developer.android.com/guide/topics/resources/runtime-changes.html

    Which means that onCreate() will be skipped on configuration changed, and you cannot swap your layout (since onCreate() is where you recreate the view).

    In your case, you want to change layout, so there is no choice but to refresh your activity, which means to remove android:configChanges="orientation|screenSize". If you want to keep the state, you can save and check the Bundle passed to your onCreate() to restore state accordingly.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // set your layoutId according to landscape/portrait
        setContentView(layoutId);
        if (savedInstanceState != null) {
            // restore your state here
        }
        ...
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // save your state here
    }
    

    For more reference: http://developer.android.com/training/basics/activity-lifecycle/recreating.html