Android Kotlin: How to change screen orientation programmatically

The code demonstrates how to programmatically change the screen orientation of an Android device. It includes three main parts:

  1. Layout: The activity_main.xml file defines the user interface layout for the activity. It consists of two buttons (btnPortrait and btnLandscape) and a text view (textView).

    • The buttons are labeled "Portrait" and "Landscape", respectively. When a user clicks a button, it triggers an event that changes the screen orientation accordingly.

    • The text view displays a message indicating that the configuration has changed and the current orientation of the device.

  2. Activity: The MainActivity.kt file implements the logic for the activity. It includes the following methods:

    • onCreate(): This method is called when the activity is first created. It sets the content view of the activity to the activity_main.xml layout and sets up click listeners for the two buttons.

      • When the user clicks the "Portrait" button, the requestedOrientation property of the activity is set to ActivityInfo.SCREEN_ORIENTATION_PORTRAIT. This requests the system to change the orientation to portrait mode.

      • When the user clicks the "Landscape" button, the requestedOrientation property of the activity is set to ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE. This requests the system to change the orientation to landscape mode.

    • onConfigurationChanged(): This method is called whenever the device configuration changes, such as when the orientation is changed. It updates the text view to display a message indicating that the configuration has changed and the current orientation.

  3. AndroidManifest.xml: The AndroidManifest.xml file specifies metadata about the Android application. In this code, the relevant part is the android:configChanges attribute in the activity declaration. This attribute is set to orientation|screenSize, which tells the system that the activity can handle changes in orientation and screen size. This is necessary because the activity is requesting orientation changes programmatically.

Overall, this code provides a simple way for users to change the screen orientation of their device by clicking buttons within the app. The onConfigurationChanged() method ensures that the activity updates its layout and behavior to reflect the new orientation.

Here is a table summarizing the key components of the code:

ComponentDescription
activity_main.xmlDefines the user interface layout for the activity
MainActivity.ktImplements the logic for the activity, including handling button clicks and orientation changes
onConfigurationChanged()Updates the text view to display the current orientation
android:configChangesSpecifies that the activity can handle changes in orientation and screen size


MainActivity.kt

package com.example.jetpack

import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnPortrait.setOnClickListener {
            // set screen orientation to portrait
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }

        btnLandscape.setOnClickListener {
            // set screen orientation to landscape
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        }
    }


    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)

        textView.text = "Configuration Changed."

        val orientation = when(newConfig.orientation){
            Configuration.ORIENTATION_PORTRAIT -> "Portrait"
            Configuration.ORIENTATION_LANDSCAPE -> "Landscape"
            Configuration.ORIENTATION_UNDEFINED -> "Undefined"
            else -> "Error"
        }

        textView.append("\nOrientation : $orientation")
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="#E5E4E2">

    <Button
        android:id="@+id/btnPortrait"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Portrait"
        android:backgroundTint="#545AA7"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnLandscape"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Landscape"
        android:backgroundTint="#C32148"
        app:layout_constraintBottom_toBottomOf="@+id/btnPortrait"
        app:layout_constraintStart_toEndOf="@+id/btnPortrait" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="16dp"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:textSize="30sp"
        android:textColor="#191970"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnPortrait"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
AndroidMenifest.xml [part]

<activity
    android:name=".MainActivity"
    android:configChanges="orientation|screenSize">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
More android kotlin tutorials