I want my Android app to only run in portrait mode?

I want my Android app to only run in portrait mode? How can I do that?

#1 building

I use

 android:screenOrientation="nosensor"

This is helpful if you do not want to support side down portrait mode.

#2 building

There are two ways,

  1. Add Android for each activity in the manifest file: screenorientation = "portait"
  2. Add this. Setrequestedorientation (activityinfo. Screen? Orientation? Landscape); in each java file.

#3 building

I know the old post. In order to always run your application in portrait mode, even if you can or swap directions and so on (for example, on a tablet), I designed this feature to set the device in the right direction without knowing how portrait and landscape functions are organized 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); }

    }

Miraculously effective!

Note: change this.activity through your activity or add it to the main activity and delete this.activity; -)

#4 building

In the list, set this for all your activities:

<activity android:name=".YourActivity"
  android:configChanges="orientation"
  android:screenOrientation="portrait"/>

#5 building

In the list, set this for all your activities:

<activity android:name=".YourActivity"
    android:configChanges="orientation"
    android:screenOrientation="portrait"/>

Let me explain:

  • Using android:configChanges="orientation" you tell Android that you will be responsible for changes in direction.
  • android:screenOrientation="portrait" you set the default orientation mode.

Tags: Android Java

Posted on Wed, 18 Mar 2020 10:06:42 -0400 by L