Wednesday, 28 September 2011

Controlling the Orientation of the Activity

"Occasionally you might want to ensure that your application is only displayed in a certain orientation."

For example, you may be writing a game that should only be viewed in landscape mode. In this
case, you can programmatically force a change in orientation using the setRequestOrientation()
method of the Activity class:





import android.content.pm.ActivityInfo;
public class MainActivity extends Activity {
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
          }


To change to portrait mode, use the ActivityInfo.SCREEN_ORIENTATION_PORTRAIT constant:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Besides using the setRequestOrientation() method, you can also use the android:screenOrientation
attribute on the <activity> element in AndroidManifest.xml as follows to constrain the activity to a
certain orientation:
 <?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”>
       <application android:icon=”@drawable/icon” android:label=”@string/app_name”>
        <activity android:name=”.MainActivity”
            android:label=”@string/app_name”
                   android:screenOrientation=”landscape” >
          <intent-filter>
      <action android:name=”android.intent.action.MAIN” />
     <category android:name=”android.intent.category.LAUNCHER” />
   </intent-filter>
</application>
<uses-sdk android:minSdkVersion=”9” />
</manifest>

Following are two other values that you can specify in the android:screenOrientation attribute:
       1.  portrait — Portrait mode
       2.  sensor — Based on the accelerometer

No comments:

Post a Comment