android – The xml is not switching when device orientation change-ThrowExceptions

Exception or error:

I have made two folders, res/layout and res/layout-land

The output i got
If I start the application in portrait mode, it will always use the xml in layout folder if the application run in portrait mode. And will not use xml in layout-land if i change the device to landscape mode
If it start in landscape mode it only use the xml in layout-land
The xml is not switching when the orientation change

What i expect was
It should use the xml in layout folder while it is in portrait mode and use the xml in layout-land while in landscape mode

In the Manifest file i have added android:configChanges="orientation" for the activity and

<supports-screens 
        android:resizeable="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:anyDensity="true" />

Did i missed any thing here? What changes i need to do here?
Thank You

How to solve:

The manifest code

android:configChanges="orientation|screenSize"

ignores the XML in “layout-land” and uses the one in the “layout” folder. If you create a different XML for landscape don’t use the android:configChanges="orientation|screenSize" tag for that activity.

###

android:configChanges=”orientation” stops the activity from restarting, so also from reloading the xml layout (you normally do this in onCreate).
Instead, onConfigurationChanged(newConfig) is called. So you can do:

@Override
    public void onConfigurationChanged(Configuration newConfig){
        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.<xml file>);
    }

This wil reload the layout from the layout-land dir, if available.
Note: you will also need to link actions to buttons and things like that

###

private void setContentBasedOnLayout()
{
    WindowManager winMan = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);

    if (winMan != null)
    {
        int orientation = winMan.getDefaultDisplay().getOrientation();

        if (orientation == 0) {
            // Portrait
            setContentView(R.layout.alertdialogportrait);
        }
        else if (orientation == 1) {
            // Landscape
            setContentView(R.layout.alertdialoglandscape);
        }            
    }
}

###

Do not forget to turn on Settings -> Display -> Auto-rotate screen option.

Leave a Reply

Your email address will not be published. Required fields are marked *