如何在 android activity 中仅禁用反向屏幕方向

How to disable only Reverse screen orientations in android activity

有什么方法可以在 android activity 中禁用反向横向和反向纵向。我使用了下面的 code.but 反向景观即将到来。

     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);
     }

将 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();
        }
    }