Jetpack Compose: Navigation

MainActivity.kt

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.neco_desarrollo.navigationcompose.ui.theme.NavigationComposeTheme

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()

NavigationComposeTheme {
NavHost(
navController = navController,
startDestination = "screen_1"
) {
composable("screen_1"){
Screen1 {
navController.navigate("screen_2")
}
}
composable("screen_2"){
Screen2 {
navController.navigate("screen_3")
}
}
composable("screen_3"){
Screen3 {
navController.navigate("screen_1"){
popUpTo("screen_1"){
inclusive = true
}
}
}
}
}
}
}
}
}

Screens.kt

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

@Composable
fun Screen1(onClick: () -> Unit) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = "Screen 1",
fontSize = 30.sp
)
Spacer(modifier = Modifier.height(30.dp))
Button(
onClick = {
onClick()
}
) {
Text(text = "Screen 2")
}
}
}
@Composable
fun Screen2(onClick: () -> Unit) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = "Screen 2",
fontSize = 30.sp
)
Spacer(modifier = Modifier.height(30.dp))
Button(
onClick = {
onClick()
}
) {
Text(text = "Screen 3")
}
}
}
@Composable
fun Screen3(onClick: () -> Unit) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = "Screen 3",
fontSize = 30.sp
)
Spacer(modifier = Modifier.height(30.dp))
Button(
onClick = {
onClick()
}
) {
Text(text = "Screen 1")
}
}
}

Зависимость Navigation:

def nav_version = "2.5.3"
implementation("androidx.navigation:navigation-compose:$nav_version")

Добавить комментарий

Ваш адрес email не будет опубликован.