为可折叠设备创建了一个演示。当设备折叠时,我想显示一种布局,当设备展开时,我有不同的布局要显示。那么如何根据配置更改来管理两种布局。?
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
Log.i(myTag, "onConfigurationChanged...")
}
为可折叠设备创建了一个演示。当设备折叠时,我想显示一种布局,当设备展开时,我有不同的布局要显示。那么如何根据配置更改来管理两种布局。?
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
Log.i(myTag, "onConfigurationChanged...")
}
您可以设置回调以接收状态:CLOSED、HALF、OPEN。
private fun setFoldableCallbacks() {
mainThreadExecutor = ContextCompat.getMainExecutor(this)
windowManager = WindowManager(this, null)
windowManager.registerDeviceStateChangeCallback(
mainThreadExecutor,
deviceStateChangeCallback
)
Handler(Looper.getMainLooper()).postDelayed({
windowManager.registerLayoutChangeCallback(mainThreadExecutor, layoutChangeCallback)
}, 1000)
}
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setcontentview();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
setcontentview();
}
看看这是否适合你。
Instead of implementing onConfigurationChanged
method you should use Jetpack WindowManager as explained by @user3471194. But keep in mind that its API has changed quite a bit, so with version 1.0.0-alpha05
WindowManager's constructor might have only one parameter (activity). Also I recommend to declare activity's configChanges in Manifest file as follows
<activity
...
android:configChanges="screenLayout|screenSize|orientation|smallestScreenSize">
...
</activity>
On the other hand, the callback you pass to registerLayoutChangeCallback
method no longer retrieves a DeviceState
object but a WindowLayoutInfo
instead, which has FoldingFeature
that might be set as STATE_FLAT
, STATE_FLIPPED
,STATE_HALF_OPENED
etc or it will be null if the device is non-foldable.