Force an Android activity to always use landscape

2019-01-02 17:12发布

I am using the Android VNC viewer on my HTC G1. But for some reason, that application is always in landscape mode despite my G1 is in portrait mode. Since the Android VNC viewer is open source, I would like know how is it possible hard code an activity to be 'landscape'. I would like to change it to respect the phone orientation.

14条回答
倾城一夜雪
2楼-- · 2019-01-02 17:26

In the manifest:

<activity  android:name=".YourActivity"
android:screenOrientation="portrait"
android:configChanges="orientation|screenSize">

In your activity:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.your_activity_layout);
查看更多
余生请多指教
3楼-- · 2019-01-02 17:32

Doing it in code is is IMO wrong and even more so if you put it into the onCreate. Do it in the manifest and the "system" knows the orientation from the startup of the app. And this type of meta or top level "guidance" SHOULD be in the manifest. If you want to prove it to yourself set a break in the Activity's onCreate. If you do it in code there it will be called twice : it starts up in Portrait mode then is switched to Landscape. This does not happen if you do it in the manifest.

查看更多
流年柔荑漫光年
4楼-- · 2019-01-02 17:37

You can set the same data in your java code as well.

myActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

Other values on ActivityInfo will let you set it back to sensor driven or locked portrait. Personally, I like to set it to something in the Manifest as suggested in another answer to this question and then change it later using the above call in the Android SDK if there's a need.

查看更多
永恒的永恒
5楼-- · 2019-01-02 17:37

Arslan, why do you want to force orientation pro grammatically, though there's already a way in manifest <activity android:name=".youractivityName" android:screenOrientation="portrait" />

查看更多
只靠听说
6楼-- · 2019-01-02 17:37

This works for Xamarin.Android. In OnCreate()

RequestedOrientation = Android.Content.PM.ScreenOrientation.Landscape;
查看更多
浪荡孟婆
7楼-- · 2019-01-02 17:38

You can specify the orientation of an activity in the manifest. See here.

<activity android:allowTaskReparenting=["true" | "false"]
...
          android:screenOrientation=["unspecified" | "user" | "behind" |
                                     "landscape" | "portrait" |
                                     "sensor" | "nosensor"]
...
                                       "adjustResize", "adjustPan"] >  
查看更多
登录 后发表回答