android - 如何在 Android Activity 中仅禁用反向屏幕方向

标签 android android-activity screen-orientation

有没有办法在 Android Activity 中禁用反向横向和反向纵向方向。我使用了下面的代码。但是反向景观即将出现。

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

关于android - 如何在 Android Activity 中仅禁用反向屏幕方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29385404/

相关文章:

android - 如何在 MotionLayout 中为缩放动画设置轴心点

android - 如何在该区域获取蓝牙配对设备

java - 在 Activity 内创建 fragment

android - 如何延迟从另一个 Activity 调用 Activity ?

java - 文件循环导致 Nexus 7 强制关闭,而不是 SGS2?

java - Android - 将 Telegram 消息发送到特定号码

java - 如何保存android Activity的状态

ios - "viewWillTransitionToSize:"在 iOS 9 中以模态方式呈现 View Controller 时未调用

android - 如何全局检测屏幕旋转何时发生变化?

java - 如何检测启动器主屏幕是否支持旋转