How to set entire application in portrait mode only?

Viewed 195050

How do I set it so the application is running in portrait mode only? I want the landscape mode to be disabled while the application is running. How do I do it programmatically?

18 Answers

Yes you can do this both programmatically and for all your activities making an AbstractActivity that all your activities extends.

public abstract class AbstractActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
}

This abstract activity can also be used for a global menu.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    //setting screen orientation locked so it will be acting as potrait
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
}

Similar to Graham Borland answer...but it seems you dont have to create Application class if you dont want...just create a Base Activity in your project

public class BaseActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_base);
    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

}

And extend this class instead of AppCompatActivity where you want to use Potrait Mode

public class your_activity extends BaseActivity {}

For Xamarin Users:

If you extends all your activities to a BaseActivity Just add:

this.RequestedOrientation = ScreenOrientation.Portrait;

This will resolve the problem. If you want any particular activity to be in landscape override this in OnActivityCreated. As:

this.Activity.RequestedOrientation = ScreenOrientation.Landscape;

Well, I tried every answer but it didn't work in older versions of android. So, the final solution is to add this code to every activity just above setContentView:

    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

In kotlin -->

Use this in your Extends Application class fun onCreate()...

registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
        override fun onActivityCreated(p0: Activity, p1: Bundle?) {
            p0.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
        }

        override fun onActivityStarted(p0: Activity) {
        }

        override fun onActivityResumed(p0: Activity) {
        }

        override fun onActivityPaused(p0: Activity) {
        }

        override fun onActivityStopped(p0: Activity) {
        }

        override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
        }

        override fun onActivityDestroyed(p0: Activity) {
        }
    }

    )}
Related