Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

kotlin - Problems with Android Jetpack Navigation

I have created an Empty Compose Activity template using Android Studio Canara 2020.03. Here is the code of the file " MainActivity. kt":

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
            setContent {
                ButtonPage()
            }
        }
}
@Composable
fun ButtonPage(){
    Button(onClick = {}){Text("Click to go next")}
}
@Composable 
fun TextPage(){
    Text("Second Page")
}

How do I modify the code so that when you click on this button, it draws only text? (That is, you need that when you click the button, the program draws other content by deleting this one first). Jetpack Compose version 1.0.0-alpha09, jdk version 15, android version 11 Thank you in advance


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A simple solution would be to have a variable that dictates the current screen.

var showSecondScreen by remember { mutableStateOf(false) }
if (!showSecondScreen) {
  Button(onClick = {showSecondScreen = true}){Text("Click to go next")}
} else {
  Text("Second screen")
}

This doesn't have to be a boolean, you could declare var currentScreen by remember { mutableStateOf("homeScreen") } and use a when block for which screen to show.

@Composable fun MyApp(currentScreen: String) {
  when (currentScreen) {
    "homeScreen" -> HomeScreen()
    "secondScreen" -> SecondScreen()
  }
}

So you can think of it less as a transaction and more as a stateful navigation.

But you'll soon realize that this doesn't handle back navigation, so you'll need a navigation library like jetpack compose navigation, decompose, compose-router, etc. Here's more information on jetpack compose navigation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...