Occasionally, you may want to make sure that your application is displayed in either landscape or Landscape mode in a certain direction. For example, you may develop a game that runs only in Landscape mode. In this case, you can write code to force the direction of the Activity to be set to horizontal, which requires the setRequestOrientation () method of the Activity class.
[Java]
Import android. content. pm. ActivityInfo;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// Set it to Landscape mode
SetRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_LANDSCAPE );
}
If you want to set it to portrait mode, you can use ActivityInfo. SCREEN_ORIENTATION_PORTRAIT constant.
In addition to the setRequestOrientation () method, you can also set it in the AndroidManifest. xml file.
[Html]
<? Xml version = "1.0" encoding = "UTF-8"?>
<Manifest xmlns: android = "http://schemas.android.com/apk/res/android"
Package = "net. learn2develop. Orientations"
Android: versionCode = "1"
Android: versionName = "1.0" type = "codeph" text = "/codeph">
<Uses-sdk android: minSdkVersion = "14"/>
<Application
Android: icon = "@ drawable/ic_launcher"
Android: label = "@ string/app_name">
<Activity
Android: label = "@ string/app_name"
Android: name = ". OrientationsActivity"
<! -- Set screenOrientation -->
Android: screenOrientation = "landscape">
<Intent-filter>
<Action android: name = "android. intent. action. MAIN"/>
<Category android: name = "android. intent. category. LAUNCHER"/>
</Intent-filter>
</Activity>
</Application>
</Manifest>
In the previous example, the contained Activity is set to the Landscape mode, and the Activity is blocked from being destroyed. This is because the Activity is set to a fixed direction. When the device direction changes, the Activity will not be destroyed, and the onCreate () method will not be called.
The following are two additional values of the android: screenOrientation attribute:
Portrait-portrait Mode
Sensor-determines the direction based on the gravity Tester (default)