Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...