[英]Android Jetpack Compose by rememberSaveable State does not survive Back Button
I cannot find the savedInstanceState
function shown in code examples in the Restore UI state after activity or process recreation section of the State and Jetpack Compose that the section says "retains state across activity and process recreation." I cannot find the
savedInstanceState
function shown in code examples in the Restore UI state after activity or process recreation section of the State and Jetpack Compose that the section says "retains state across activity and process recreation."
I did find the androidx.compose.runtime.saveable
documentation which contains rememberSaveable
which seems to be the renaming or replacement of savedInstanceState
and its documentation also says "... the stored value will survive the activity or process recreation."我确实找到了包含
rememberSaveable
的androidx.compose.runtime.saveable
文档,它似乎是对savedInstanceState
的重命名或替换,它的文档还说“......存储的值将在活动或进程重新创建后继续存在。”
However, when I use it in my code, the state does not survive the back button, although it does survive rotations.然而,当我在我的代码中使用它时,state 不能在后退按钮中存活,尽管它可以在旋转中存活。 That's contrary to what the documentation says.
这与文档所说的相反。
package com.example.jetwatch
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.material.*
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
class MainActivity : AppCompatActivity() {
override fun onCreate(bundle: Bundle?) {
super.onCreate(bundle)
setContent {
MaterialTheme(colors = if (isSystemInDarkTheme()) darkColors() else lightColors()) {
Surface {
Column {
Row {
Column {
var m by rememberSaveable { mutableStateOf(0) }
Text("m = $m")
Button(onClick = { ++m }) {
Text("bump")
}
}
}
}
}
}
}
}
}
the state does not survive the back button
state 无法使用后退按钮
In that sample, this is expected behavior.在该示例中,这是预期的行为。 The default behavior of back navigation is to destroy the activity.
后退导航的默认行为是销毁活动。 Saved instance state is discarded at this point.
保存的实例 state 此时被丢弃。 This is not unique to Compose and has been stock Android behavior since Android 1.0.
这不是 Compose 独有的,并且自 Android 1.0 以来一直存在 Android 行为。
That's contrary to what the documentation says.
这与文档所说的相反。
"Process termination", as used in the documentation, refers to this flow:文档中使用的“流程终止”是指此流程:
At that point, Android will fork a fresh process for you and try to restore your UI to where you had been before the user switched away from your app.届时,Android 将为您创建一个新进程,并尝试将您的 UI 恢复到用户离开您的应用程序之前的位置。 The saved instance state is part of that restoration.
保存的实例 state 是该恢复的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.