How do i detect device orientation in android using kotlin code
Published October 07, 2022In this android example we will learn how to detect device orientation programmatically. When device rotate activity onConfigurationChanged will trigger and we can fetch the current orientation of the device using Configuration instance.
let get started
1. Create Android application
2. Add below code in activity class
package rrtutors.com.androidtopactivity import android.content.pm.ActivityInfo import android.content.res.Configuration import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.DisplayMetrics import android.view.View import android.widget.TextView import android.widget.Toast import org.w3c.dom.Text class SDkVersion : AppCompatActivity() { lateinit var txt_info: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sdk_version) txt_info=findViewById(R.id.txt_info) } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE) Toast.makeText(applicationContext,"Orientation Landscape",Toast.LENGTH_SHORT).show() else Toast.makeText(applicationContext,"Orientation Portrait",Toast.LENGTH_SHORT).show() } } |
3. Now run application and rotate the device. Each rotation activity will called onConfigurationChanged method and will display the current orientation as toast message
Article Contributed By :
|
|
|
|
284 Views |