typealias Actions = @Composable () -> Unit
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
SampleAppTheme {
var currentScreen by remember { mutableStateOf(Screen.A) }
var title by remember { mutableStateOf("Screen A") }
var action by remember { mutableStateOf<Actions>({}) }
Scaffold(
topBar = {
TopAppBar(
title = {
Text(title)
},
actions = {
action()
}
)
}
) {
Crossfade(current = currentScreen) { screen ->
when (screen) {
Screen.A -> {
MyScreen(
name = "A",
buttonName = "to Screen B",
onNext = {
currentScreen = Screen.B
title = "Screen B"
action = {
IconButton(onClick = {}) {
Icon(asset = Icons.Sharp.Home)
}
}
}
)
}
Screen.B -> {
MyScreen(
name = "B",
buttonName = "to Screen C",
onNext = {
currentScreen = Screen.C
title = "Screen B"
action = {
IconButton(onClick = {}) {
Icon(asset = Icons.Sharp.Close)
}
}
}
)
}
Screen.C -> {
MyScreen(
name = "C",
buttonName = "to Screen A",
onNext = {
currentScreen = Screen.A
title = "Screen A"
action = {}
}
)
}
}
}
}
}
}
}
}
enum class Screen {
A, B, C
}
@Composable
fun MyScreen(
name: String,
buttonName: String,
onNext: () -> Unit,
) {
Column(
Modifier.fillMaxSize().padding(24.dp),
) {
Text(
modifier = Modifier.weight(1f),
text = "I am in screen $name!",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h3
)
Button(
modifier = Modifier.fillMaxWidth(),
onClick = onNext
) {
Text(text = buttonName)
}
}
}
因此,使用此代码,我将看到以下屏幕:
请注意,通过执行以下操作,可以根据当前屏幕更改Actions
中的TopAppBar
:
MyScreen(
name = "B",
buttonName = "to Screen C",
onNext = {
currentScreen = Screen.C
title = "Screen B"
// This right here!!!! -------------------
action = {
IconButton(onClick = {}) {
Icon(asset = Icons.Sharp.Close)
}
}
// This right here!!!! -------------------
}
)
我的第一个问题是这是否是正确的方法?
对于第二个问题,我觉得我在上一个屏幕中设置的值应该由当前屏幕负责。所以我尝试这样做?
Screen.B -> {
// This right here!!!! -------------------
onActive {
title = "Screen B"
action = {
IconButton(onClick = {}) {
Icon(asset = Icons.Sharp.Home)
}
}
}
// This right here!!!! -------------------
MyScreen(
name = "B",
buttonName = "to Screen C",
onNext = {
currentScreen = Screen.C
}
)
}
所以现在,设置状态的责任在当前屏幕上,而不是以前的屏幕上。
这样好吗?
经过一些测试:显然是从屏幕A->屏幕B->屏幕C转移到onActive { }
被称为错误的顺序。因此,在某些状态下,屏幕B以屏幕A为标题...屏幕C以屏幕B为标题,依此类推...
即使意识到第一种方法也有缺陷,因为您还必须在返回屏幕时设置状态。.让我们说一下...屏幕A->屏幕B->屏幕C->按下(屏幕B)...现在状态错了...
答案 0 :(得分:0)
我想这个问题可以使用 Jetpack Navigation for Compose 来解决。
https://developer.android.com/jetpack/compose/navigation
也许这篇文章能帮到你...