Study Record

[Android] Compose 앱바와 Navigation 연결하기 본문

안드로이드/compose

[Android] Compose 앱바와 Navigation 연결하기

초코초코초코 2023. 11. 17. 16:02
728x90

 

😶 Compose 앱바와 Navigation 연결하기

 

앱바를 구현할 때 Scaffold 컴포저블의 topBar 와 Navigation 을 사용하면  rememberNavController 를 이용해 앱바와 Navigation 을 연결할 수 있다.

 

 

앱바의 뒤로가기 아이콘을 구현할 경우 뒤로 가기 버튼을 누르면 이전 화면으로 이동해야 한다. 전체 코드는 다음과 같다.

@Composable
fun LunchTrayApp() {
    //Create NavController
    val navController = rememberNavController()
    // Get current back stack entry
    val backStackEntry by navController.currentBackStackEntryAsState()
    // Get the name of the current screen
    val currentScreen = LunchTrayScreen.valueOf(
        backStackEntry?.destination?.route ?: LunchTrayScreen.Start.name
    )

    Scaffold(
        topBar = {
            LunchTrayAppBar(
                currentScreenTitle = currentScreen.title,
                canNavigateBack = navController.previousBackStackEntry != null,
                navigateUp = { navController.navigateUp() }
            )
        }
    ) { innerPadding -> 
        NavHost(
            navController = navController,
            startDestination = "First_Page",
        ) { /* */ }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LunchTrayAppBar(
    @StringRes currentScreenTitle: Int,
    canNavigateBack: Boolean,
    navigateUp: () -> Unit,
    modifier: Modifier = Modifier
) {
    CenterAlignedTopAppBar(
        title = { Text(stringResource(currentScreenTitle)) },
        modifier = modifier,
        navigationIcon = {
            if (canNavigateBack) {
                IconButton(onClick = navigateUp) {
                    Icon(
                        imageVector = Icons.Filled.ArrowBack,
                        contentDescription = stringResource(R.string.back_button)
                    )
                }
            }
        }
    )
}

 

 

앱바를 표현하는 CeterAlignedTopAppBar 의 네비게이션 아이콘은 navigationIcon 인자가 담당한다. 

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LunchTrayAppBar(
    @StringRes currentScreenTitle: Int,
    canNavigateBack: Boolean,
    navigateUp: () -> Unit,
    modifier: Modifier = Modifier
) {
    CenterAlignedTopAppBar(
        title = { Text(stringResource(currentScreenTitle)) },
        modifier = modifier,
        navigationIcon = {
            if (canNavigateBack) {
                IconButton(onClick = navigateUp) {
                    Icon(
                        imageVector = Icons.Filled.ArrowBack,
                        contentDescription = stringResource(R.string.back_button)
                    )
                }
            }
        }
    )
}

 

 

728x90