- 从一项活动更改为另一项活动后,我正在尝试保存我的编辑文本值
- 例如:就像在注册寻呼机中一样(首先您必须在页面中填写所有数据,最后提交。
- 我在这里遇到问题是如果我想编辑我的第一页数据所以我从第二页移动到第一页但我的第一页没有显示任何数据
- 我尝试使用保存状态和恢复导航状态,但无济于事
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { ScreenNavigation() }
}
}
@Composable
fun Page1(navController: NavHostController) {
var test = remember { mutableStateOf("") }
Column() {
TextField(value = test.value, onValueChange = { test.value = it })
Button(
onClick = {
navController.navigate(ScreenRoute.Page2.name) {
popUpTo(ScreenRoute.Page2.name) { saveState = true }
launchSingleTop = true
restoreState = true
}
}
) {}
Text(text = "Page1")
TextField(
value = test.value,
onValueChange = { test.value = it },
)
}
}
@Composable
fun Page2(navController: NavHostController) {
var test = remember { mutableStateOf("") }
Column() {
TextField(value = test.value, onValueChange = { test.value = it })
Button(
onClick = {
navController.navigate(ScreenRoute.Page1.name) {
popUpTo(ScreenRoute.Page1.name) { saveState = true }
launchSingleTop = true
restoreState = true
}
}
) {}
Text(text = "Page2")
}
}
// code for navigation
@Composable
fun ScreenNavigation() {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = ScreenRoute.Page1.name) {
composable(ScreenRoute.Page1.name) { Page1(navController) }
composable(ScreenRoute.Page2.name) { Page2(navController) }
}
}
// code for screen route
enum class ScreenRoute {
Page1,
Page2,
}