nikib3ro
nikib3ro

Reputation: 20606

How to set the activity content based on the current screen orientation?

I simply want to do:

if(getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
    setContentView(R.layout.search_portrait);
else
    setContentView(R.layout.search_landscape);

The problem is - getRequestedOrientation always returns -1.

Any suggestions?

Upvotes: 1

Views: 2251

Answers (3)

Aamir
Aamir

Reputation: 16967

It must works properly, use this

 if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_LANDSCAPE)

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    else
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

setContentView(R.layout.main_activity);

And also place landscape xml file in

/res/layout-land

Note: Layout file name must be same in all layout directories

i.e

  • res/layout/activity_main
  • res/layout-land/activity_main

Upvotes: 0

Dave
Dave

Reputation: 6104

If you're just changing the layout, you should really think about putting your portrait layouts in /res/layout and your landscape layouts in /res/layout-land (with the same names) and Android will select the correct layout automatically.

Upvotes: 5

Cristian
Cristian

Reputation: 200090

Try adding android:screenOrientation="portrait" or android:screenOrientation="landscape" to your manifest for this activity. It will be the default orientation... that's because getRequestedOrientation "Return the current requested orientation of the activity. This will either be the orientation requested in its component's manifest, or the last requested orientation given to setRequestedOrientation(int).".

Upvotes: 1

Related Questions