Вы можете сделать функцию расширения из приведенного выше кода:
fun AppCompatActivity.getRotation(): Int{
val display = (baseContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
val rotation = display.rotation
when(rotation){
Surface.ROTATION_90 -> return R.integer.LANDSCAPE
Surface.ROTATION_270 -> return R.integer.LANDSCAPE
Surface.ROTATION_180 -> return R.integer.PORTRAIT
Surface.ROTATION_0 -> return R.integer.PORTRAIT
else ->
return R.integer.PORTRAIT
}
}
В своем каталоге ресурсов создайте файл constants.xml
со следующим содержимым:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="LANDSCAPE">0</integer>
<integer name="PORTRAIT">1</integer>
</resources>
Ваш кодтогда так же просто, как (например, вертикальное / горизонтальное расположение для Recyclerview во фрагменте:
val a = activity as AppCompatActivity
val orientation = a.getRotation()
when (orientation){
R.integer.PORTRAIT -> rv.layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL,false)
R.integer.LANDSCAPE -> rv.layoutManager = LinearLayoutManager(activity, RecyclerView.HORIZONTAL,false)
}