在Android中要讓一個程序的界面始終保持一個方向,不隨手機方向轉動而變化的辦法: 只要在AndroidManifest.xml裡面配置一下就可以了。
在AndroidManifest.xml的activity(需要禁止轉向的activity)配置中加入android:screenOrientation=”landscape”屬性即可(landscape是橫向,portrait是縱向)。
另外,android中每次屏幕方向切換時都會重啟Activity,所以應該在Activity銷毀前保存當前活動的狀態,在Activity再次Create的時候載入配置。要避免在轉屏時重啟activity,可以通過在androidmanifest.xml文件中重新定義方向(給每個activity加上android:configChanges=”keyboardHidden|orientation”屬性),並根據Activity的重寫onConfigurationChanged(Configuration newConfig)方法來控制,這樣在轉屏時就不會重啟activity了,而是會去調用onConfigurationChanged(Configuration newConfig)這個方法。
示例代碼如下:
[html]
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.liananse.ideal"
- android:versionCode="1"
- android:versionName="1.1" >
-
- <uses-sdk android:minSdkVersion="10" />
-
- <application
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name" >
- <activity
- android:label="@string/app_name"
- android:name="com.liananse.WelcomeActivity"
- android:screenOrientation="portrait"
- android:configChanges="keyboardHidden|orientation">
- <intent-filter >
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <activity
- android:name="com.liananse.activity.MainActivity"
- android:screenOrientation="portrait"
- android:configChanges="keyboardHidden|orientation"></activity>
- <activity
- android:name="com.liananse.activity.MusicActivity"
- android:screenOrientation="portrait"
- android:configChanges="keyboardHidden|orientation"></activity>
- <activity
- android:name="com.liananse.activity.config.IdealAbout"
- android:theme="@android:style/Theme.NoTitleBar"
- android:screenOrientation="portrait"
- android:configChanges="keyboardHidden|orientation"></activity>
- <activity
- android:name="com.liananse.activity.config.IdealSetting"
- android:theme="@android:style/Theme.NoTitleBar"
- android:screenOrientation="portrait"
- android:configChanges="keyboardHidden|orientation"></activity>
- <activity
- android:name="net.youmi.android.AdActivity"
- android:configChanges="keyboard|keyboardHidden|orientation"
- android:screenOrientation="portrait"/>
- <meta-data android:name="YOUMI_CHANNEL" android:value="0" />
- </application>
- <uses-permission android:name="android.permission.INTERNET"/>
- <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- </manifest>