androiduser
androiduser

Reputation: 977

how to provide separate layouts for portrait and landscape mode in android

I am working with a Real time app which contains Tabs through out the application. When I try to switch the orientation between portrait and landscape, I have code to show a separate layout for landscape. For this I have used the onConfigurationChanged method as follows

public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);
    if(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT){
        setContentView(R.layout.eventslist);
    }else if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
        setContentView(R.layout.eventstimeline);
    }
}

And also in the manifest file for that particular activity I have used two attributes as follows

android:screenOrientation="sensor"

android:configChanges="orientation|keyboardHidden"

But when I rotate the device I cannot see the separate layout for the landscape mode which I have specified in onConfigurationChanged. Also I don't want to see the tabs in the landscape mode. Any idea about this.

Upvotes: 1

Views: 2938

Answers (2)

jobesu
jobesu

Reputation: 620

If you don't care that your activity is recreated when you change orientation, just create your layouts xml files for portait and landscape with the same name and put the one for portait in the layout folder and the one for landscape in layout-land folder. Then you can do

protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.xml_with_same_name_for_landscape_and_portait);
}

If you don't want to desrtoy and recreate your activity each time the orientation changes, it seems that you are doing well, but the Activity doc says:

If a configuration change involves any that you do not handle, however, the activity will still be restarted and onConfigurationChanged(Configuration) will not be called.

So perhpas your problem is onConfigurationChanged() is never called. In this case chek yout android:configChanges attribute in the manifest.

Upvotes: 1

vbokan
vbokan

Reputation: 133

In Resources you can define different layout for each orientation, similar to drawables with screen density.

Beside layout folder, you can put layouts in:

layout-port : layout for portrait orientation

layout-land : layout for landscape orientation

Ofcourse, you should use same name for those layouts, same as with drawables.

Then just setContentView(R.layout.thatlayout);

Upvotes: 6

Related Questions