Jetpack Compose 方向

Sir*_*lon 16 android android-jetpack-compose

Jetpack Compose 中是否有任何 Orientation helpers 类,就像 Flutter 有https://flutter.dev/docs/cookbook/design/orientation 一样?我需要知道何时更改了方向以正确调整我的布局。

Mut*_*ran 23

我们可以LocalConfiguration用来监听方向变化

@Composable
fun ConfigChangeExample() {
    val configuration = LocalConfiguration.current
    when (configuration.orientation) {
        Configuration.ORIENTATION_LANDSCAPE -> {
            Text("Landscape")
        }
        else -> {
            Text("Portrait")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:这不会帮助监听配置更改,这只会帮助获取当前配置。

  • 当配置更改后活动被销毁和创建时,所有可兼容项是否都会被重组? (7认同)

Tom*_*Tom 15

为了观察方向,我们可以创建一个快照流来观察方向的变化,该变化将输入到您可以直接使用的状态变量中。

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()
    }
}
Run Code Online (Sandbox Code Playgroud)


San*_*Sur 5

我们可以在 jectpack compose 中使用状态,以便可组合项在状态更改时重新组合自身。

configuration change聆听使用的示例state如下:-

@Composable
fun ShowConfig(config: String) {
   Text(text = "$config!")
}
Run Code Online (Sandbox Code Playgroud)

保持config state活动状态:-

var state by mutableStateOf("Potrait")
Run Code Online (Sandbox Code Playgroud)

然后监听活动中的配置更改,并在配置中仅按以下值更新状态:-

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
    }
}
Run Code Online (Sandbox Code Playgroud)

只要配置字符串的状态发生更改,Greeting 可组合项就会观察配置字符串的状态并重新组合。