![](/img/trans.png)
[英]Jetpack Compose rememberSaveable() leads to crash when an app goes to background
[英]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."
我確實找到了包含rememberSaveable
的androidx.compose.runtime.saveable
文檔,它似乎是對savedInstanceState
的重命名或替換,它的文檔還說“......存儲的值將在活動或進程重新創建后繼續存在。”
然而,當我在我的代碼中使用它時,state 不能在后退按鈕中存活,盡管它可以在旋轉中存活。 這與文檔所說的相反。
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")
}
}
}
}
}
}
}
}
}
state 無法使用后退按鈕
在該示例中,這是預期的行為。 后退導航的默認行為是銷毀活動。 保存的實例 state 此時被丟棄。 這不是 Compose 獨有的,並且自 Android 1.0 以來一直存在 Android 行為。
這與文檔所說的相反。
文檔中使用的“流程終止”是指此流程:
屆時,Android 將為您創建一個新進程,並嘗試將您的 UI 恢復到用戶離開您的應用程序之前的位置。 保存的實例 state 是該恢復的一部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.