Search code examples
android-activityorientationscreen-orientation

Android cannot set screenOrientation,


I have read through every post I could find on this and other sites and followed the advice, but in the most simple implementation I cannot get the Note 5 to set to Portrait mode when it is physically in Landscape orientation. I added the lines as recommended to the manifest file, rebuilt and the app starts in Landscape mode.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.twistlogic.miwidget">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:configChanges="orientation"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I also tried doing this with code, which is my main purpose:

    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

nothing is produced that works.

I am trying to learn Android so I understand this may well be due to my limited knowledge. What I am trying to do is fix the orientation and lock it there, then allow it to change only when the user pushes a button. I did read that the screen size had to be set after API 13. But I am not certain how to do so. I am using a fragment template screen from the basic activities when the project was created.

Thanks for any help.


Solution

  • This can be set in the Main Activity I have not tried to set it in the Manifest here is a single line of code and a few lines to write a test Ok here is the Manifest code at the end

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    
    int orientation = getResources().getConfiguration().orientation;
    if(orientation ==  Configuration.ORIENTATION_PORTRAIT){
    
    }else if(orientation ==  Configuration.ORIENTATION_LANDSCAPE){}
    

    In your manifest file after your main activity Paste below line.

    android:screenOrientation="portrait"

    I have not tested this code in a Manifest file