In this post we are going to learn how to set screen orientation programatically in Android
Let's Start
Step 1: Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project
Step 2: Updated xml file with below code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:layout_centerInParent="true"
android:gravity="center"
android:text="Screen Orientation programmatically"
android:textSize="24sp"
android:textStyle="bold"/>
<Button
android:id="@+id/btnButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Orientation"
android:background="@color/colorPrimary"
android:textColor="@color/white"
android:layout_margin="16dp"
android:minEms="10"
/>
</LinearLayout>
|
Step 3: Updated Activity file with below code
package com.rrtutors.androidsamples
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_screen_orientation.*
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import androidx.core.app.ComponentActivity.ExtraData
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
class ScreenOrientationActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_screen_orientation)
btnButton.setOnClickListener(object : View.OnClickListener{
override fun onClick(v: View?) {
val currentOrientation = resources.configuration.orientation
if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
} else {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}
}
})
}
}
|
Step 4: Run application
Article Contributed By :
|
|
|
|
2563 Views |