How to Change the Screen Orientation Programmatically using a Button in Android?
Generally, the screen orientation of any application is Portrait styled. But when it comes to gaming or any other multimedia service such as watching a video, the screen orientation must change functionally from Portrait to landscape or vice-versa when the functionality is not required. So a developer has to explicitly write a program where the orientation changes without the user to invoke it traditionally by switching on and off the rotate/auto-rotate available in the swipe-down menu.
The main focus of changing the screen to landscape mode is to increase the area of action and response, and back to normal when not required. The latter can be neglected if there is a direct exit from the application. So this is not an application, instead, it is a feature, that can be given to any application. Some of the applications are where this feature can be added are:
- Gaming Applications: As previously mentioned. Landscape view gives better accessibility to the screen for touch in Gaming applications.
- Videos Application: Applications broadcasting multimedia such as a video can enable this feature to view the same video by utilizing each screen’s pixel.
- Photo Editing Applications: This feature can help the user view the changes and compare two different portions of the image as the display size has now increased.
- Applications requiring multiple user inputs: such as a notepad, or a browser, where a user can read the entire line or paragraphs that are being written or applications.
In this application, we will create this feature and keep it explicit, i.e., a Button should be clicked to make the changes. The code in the latter section of the article is limited to the created application only. Screen Orientation changed inside the application make no changes outside the application, i.e., the orientation outside the application remains the same as previously. Note that we are going to implement this project using the Kotlin language.
Steps for Changing the Screen Orientation Programmatically using a Button
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
When the setup is ready, go to the activity_main.xml file, which represents the UI of the project. Create a Button that changes the screen orientation on click. Below is the code for the activity_main.xml file.
Step 3: Working with the MainActivity.kt file
In the MainActivity.kt file, declare the Button to change screen orientation (refer to the codes). While setting the onClickListeners to the Button, orientation request is sent to the ActivityInfo. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.