Created
March 22, 2023 22:31
-
-
Save dnfield/8e2d28343e68cbc95ea0bbd5c378f29b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.onsizechange | |
import android.app.Activity | |
import android.content.pm.ActivityInfo | |
import android.content.res.Configuration | |
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import android.util.Log | |
import android.view.View | |
import androidx.window.layout.WindowMetricsCalculator | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(object : View(this) { | |
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { | |
super.onSizeChanged(w, h, oldw, oldh) | |
val widthDp = w / resources.displayMetrics.density | |
Log.e("OSC", "onSizeChanged: to ($w x $h) from: ($oldw x $oldh) widthDp: $widthDp") | |
if (widthDp < 600) { | |
(context as Activity).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) | |
} else { | |
(context as Activity).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) | |
} | |
} | |
override fun onConfigurationChanged(newConfig: Configuration?) { | |
super.onConfigurationChanged(newConfig) | |
val metrics = WindowMetricsCalculator.getOrCreate() | |
.computeCurrentWindowMetrics(this) | |
val widthDp = metrics.bounds.width() / | |
resources.displayMetrics.density | |
Log.e("OSC", "Configuration change widthDp: $widthDp") | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment