I want my android application to be only run in portrait mode?

前端 未结 6 2028
温柔的废话
温柔的废话 2020-11-30 16:26

I want my android application to be only run in portrait mode? How can I do that?

6条回答
  •  鱼传尺愫
    2020-11-30 17:13

    Old post I know. In order to run your app always in portrait mode even when orientation may be or is swapped etc (for example on tablets) 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!

    NOTICE: Change this.activity by your activity or add it to the main activity and remove this.activity ;-)

提交回复
热议问题