[英]Can't use reverse portrait orientation without “Auto-Rotate Screen” enabled
[英]Android: How to force reverse portrait orientation even if the device auto-rotate screen is off?
我正在開發一款應在多人游戲模式下在portrait
和reversePortrait
portrait
之間切換的應用/游戲。 (主要是因為當設備固定在他們之間的桌子上時,每個玩家都可能在回合時使用鍵盤。)
當自動旋轉功能打開時,我的應用程序運行正常。但是,當設備自動旋轉功能關閉時,則reversePortrait
實現reversePortrait
方向!
到目前為止,我所做的是在Manifest
文件中設置了方向:
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
然后在需要時通過調用此方法在運行時以編程方式更改方向:
public void rotateScreen(boolean reverse){
if (reverse) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
}
else{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
但是,如果設備的自動旋轉功能為“關閉”,這仍然不會強制reversePortrait
方向。
我也嘗試了onConfigurationChanged()
方法,但效果不佳。 我認為只有在更改方向之后才調用它,而不是之前!
我什screenOrientation="reversePortrait"
在Manifest
文件中嘗試過screenOrientation="reversePortrait"
,但是當自動旋轉設置為OFF時,即使這樣也無效。
我不知道您到底想實現什么。 在OnConfigurationChanged中調用您的方法
@Override
public void onConfigurationChanged(Configuration newConfig) {
rotateScreen(true);
super.onConfigurationChanged(newConfig);
}
但是在這里,一旦首次啟動,屏幕就會反轉,但是您可以根據需要進行應用。
請提供更多詳細信息您要達到的目標
經過大量研究,似乎覆蓋設備鎖定方向並將屏幕設置為反向縱向的唯一方法是強制啟用設備自動旋轉。
首先,必須在標簽上方的清單文件中添加此權限:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
然后,在mainActivity中定義類似的內容:
public boolean enableAutoRotate(){
boolean isAutoRotate = android.provider.Settings.System
.getInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 1) == 1;
if (!isAutoRotate){
try {
android.provider.Settings.System
.putInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 1);
} catch (Exception e){
e.printStackTrace();
}
}
isAutoRotate = android.provider.Settings.System
.getInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 1) == 1;
return isAutoRotate;
}
如果用戶未提供或刪除權限,則嘗試捕獲對防止應用程序崩潰很重要。
然后,在需要時使用以下方法設置方向:
public void rotateScreen(boolean reverse){
if (enableAutoRotate()){
if (reverse) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
如果需要,rotateScreen方法也可以是布爾值而不是void。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.