Check orientation on Android phone

前端 未结 23 1637
庸人自扰
庸人自扰 2020-11-22 06:26

How can I check if the Android phone is in Landscape or Portrait?

23条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 06:57

    Old post I know. Whatever the orientation may be or is swapped etc. I designed this function that is used to set the device in the right orientation without the need to know how the portrait and landscape features are organised on the device.

       private void initActivityScreenOrientPortrait()
        {
            // Avoid screen rotations (use the manifests android:screenOrientation setting)
            // Set this to nosensor or potrait
    
            // Set window fullscreen
            this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    
            DisplayMetrics metrics = new DisplayMetrics();
            this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
    
             // Test if it is VISUAL in portrait mode by simply checking it's size
            boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels ); 
    
            if( !bIsVisualPortrait )
            { 
                // Swap the orientation to match the VISUAL portrait mode
                if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
                 { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
                else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
            }
            else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }
    
        }
    

    Works like a charm!

提交回复
热议问题