Labeeb Panampullan
Labeeb Panampullan

Reputation: 34823

The xml is not switching when device orientation change


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

Upvotes: 22

Views: 14364

Answers (4)

Siddharth Lele
Siddharth Lele

Reputation: 27748

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.

Upvotes: 44

kolobok_ua
kolobok_ua

Reputation: 4190

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

Upvotes: 2

user4082794
user4082794

Reputation:

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);
        }            
    }
}

Upvotes: 1

Barryvdh
Barryvdh

Reputation: 6579

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

Upvotes: 24

Related Questions