Android Jetpack组件的定位
在Jetpack Compose中有没有像Flitter那样的定向助手课程?? 我需要知道方向何时改变,以便正确调整布局。我们可以使用来收听方向的改变Android Jetpack组件的定位,android,android-jetpack-compose,Android,Android Jetpack Compose,在Jetpack Compose中有没有像Flitter那样的定向助手课程?? 我需要知道方向何时改变,以便正确调整布局。我们可以使用来收听方向的改变 @Composable fun ConfigChangeExample() { val configuration = LocalConfiguration.current when (configuration.orientation) { Configuration.ORIENTATION_LANDSCAPE
@Composable
fun ConfigChangeExample() {
val configuration = LocalConfiguration.current
when (configuration.orientation) {
Configuration.ORIENTATION_LANDSCAPE -> {
Text("Landscape")
}
else -> {
Text("Portrait")
}
}
}
注意:这无助于侦听配置更改,这只会帮助获取当前配置。我们可以在jectpack compose中使用,以便可组合程序在状态更改时重新组合自身
使用状态
收听配置更改
的示例如下:-
@Composable
fun ShowConfig(config: String) {
Text(text = "$config!")
}
在活动中保持配置状态
:-
var state by mutableStateOf("Potrait")
然后收听活动中的配置更改,在配置时只需按如下值更新状态:-
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
state = "Landscape" // this will automatically change the text to landscape
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
state = "Potrait" // this will automatically change the text to potrait
}
}
每当配置字符串的状态发生变化时,Greeting composable就会观察配置字符串的状态。要观察方向,我们可以创建一个快照流来观察方向的变化,该快照流将输入到可直接使用的状态变量中
var orientation by remember { mutableStateOf(Configuration.ORIENTATION_PORTRAIT) }
val configuration = LocalConfiguration.current
// If our configuration changes then this will launch a new coroutine scope for it
LaunchedEffect(configuration) {
// Save any changes to the orientation value on the configuration object
snapshotFlow { configuration.orientation }
.collect { orientation = it }
}
when (orientation) {
Configuration.ORIENTATION_LANDSCAPE -> {
LandscapeContent()
}
else -> {
PortraitContent()
}
}
杰出的谢谢有趣的…我不确定是否值得,我还在学习!