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 - getRequestedO开发者_StackOverflow中文版rientation always returns -1.
Any suggestions?
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.
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).".
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
精彩评论