2015-04-01 104 views
1

有什麼方法可以在android活動中禁用反向風景和反向縱向方向。我使用了下面的代碼,但逆向風景即將到來。如何僅在Android活動中禁用反向屏幕方向

 rotation = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getRotation(); 
    System.out.println("Rotation Value : " +rotation); 
    if(rotation==0){ 
     System.out.println("portrait"); 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);} 
    if(rotation==1){ 
     System.out.println("landscape"); 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);} 

    if(rotation==2) 
    { 
     System.out.println("reverse portrait"); 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED); 
    } 
    if(rotation==3) 
    { 
     System.out.println("reverse landscape"); 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED); 
    } 

回答

2

將android:configChanges =「keyboardHidden | orientation」添加到您的AndroidManifest.xml中。這告訴系統你將要處理自己的配置變化,在這種情況下什麼也不做。

<activity 
android:name="MainActivity" 
android:screenOrientation="portrait" //This line only if you want to lock your screen Orientation 
android:configChanges="keyboardHidden|orientation|screenSize"> 

檢查http://developer.android.com/reference/android/R.attr.html#configChanges瞭解更多詳情。

然後覆蓋onConfigurationChanged: http://developer.android.com/guide/topics/resources/runtime-changes.html

@Override 
    public void onConfigurationChanged(Configuration newConfig) { 
     super.onConfigurationChanged(newConfig); 

     // Checks the orientation of the screen 
     if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { 
      Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show(); 
     } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ 
      Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show(); 
     } 
    } 
+0

然後將我在我的活動類重寫onConfigurationChanged()??? – 2015-04-01 08:05:24

+0

剛剛編輯我的帖子 – 2015-04-01 08:28:07

+0

謝謝你的帖子。這工作。但是如何阻止逆向取向呢? – 2015-04-01 08:55:58