Locking Screen Orientation in Android
If there is a scenario where you need your entire application to be in portrait mode or landscape mode or one of the Activity should be in portrait mode and all the other activities should be set at auto screen orientation, then here this article makes you do that in simple steps. So in this article, we are going to learn the following two things.
- How to make the entire application to be in portrait mode or landscape mode? Here is a preview of an entire application to be in portrait mode:
- And how to make one of the Activity should be in portrait mode and all the other activities should be set at auto screen orientation? Here is a preview for the same:
Steps for Locking Screen Orientation
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 Java as the programming language. Rename the MainActivity file as Activity1 and acticity_main as layout_activity_1 (renaming is done to avoid confusion between two activities).
Note: To rename the file click on the MainActivity -> Right-click -> Refactor -> Rename and similarly do for acticity_main file.
Step 2: Create another empty activity
Now create another empty activity by right click on app -> New -> Activity -> Empty Activity and rename the activity with Activity2 and also rename the layout name as layout_activity_2. Refer below images if you are unable to get the above steps.
Step 3: Working with the layout_activity_1.xml file
One needs to include text and button in the layout_activity_1. So open the layout_activity_1.xml and add widgets TextView and Button as these are been included so that we can differentiate the 2 activities.
Output UI is produced as:
Step 4: Working with the Activity1.java file
Now you need to handle the above Goto Activity 2 button. So now open Activity1.java and handles the button as invoking the following code. Refer this for Explicit Intents: Android | Implicit and Explicit Intents with Examples and for handling click events of buttons in android you may refer to this: Handling Click events in Button | Android.
Step 5: Working with the layout_activity_2.xml file
Now open the layout_activity_2.xml and add widgets TextView and Button.
Output UI is produced as :
Step 6: Working with the Activity2.java file
We need to handle the above Goto Activity 1 button. To handle this button open Activity2.java and invoke the following code:
- After modification of the AndroidManifest file the app should behave like: