상세 컨텐츠

본문 제목

안드로이드/Android 의 (Compose) - 스낵바 사용 방법(Snackbar)

Android 자료실/기능 개발

by Victorywskim 2024. 1. 7. 01:17

본문

반응형

스낵바는 화면 하단에 표시되는 간단한 알림의 역할을 합니다.

 

안드로이드에서 알림 역할을 하는 것은 다이얼로그(Dialog), 토스트(Toast), 그리고 스낵바(Snackbar) 가 있습니다.

 

스낵바는 토스트와 상당 부분 유사한 부분이 있는데 그것은 몇 초 후에 사라진다는 부분입니다.

그 외 차이점이라고 한다면 버튼 탭하기와 같은 작업으로 알림을 닫을 수도 있다는 점입니다.

 

설명은 이정도로 마치고 실질적인 사용 방법에 대해 알아보겠습니다.

 

사용 방법은 크게 Scaffold 를 이용할때와 아닐때 2가지로 구분됩니다.

 

Scaffold 내 적용하는 경우

 

기본으로 적용하는 방법

val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
Scaffold(
    snackbarHost = {
        SnackbarHost(hostState = snackbarHostState)
    },
    floatingActionButton = {
        ExtendedFloatingActionButton(
            text = { Text("플로팅 버튼명") },
            icon = { Icon(Icons.Filled.Image, contentDescription = "") },
            onClick = {
                scope.launch {
                    snackbarHostState.showSnackbar("스낵바 제목")
                }
            }
        )
    }
) { contentPadding ->
    // Screen content
}

 

 

작업을 추가하여 적용하는 방법

val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
Scaffold(
    snackbarHost = {
        SnackbarHost(hostState = snackbarHostState)
    },
    floatingActionButton = {
        ExtendedFloatingActionButton(
            text = { Text("플로팅 버튼명") },
            icon = { Icon(Icons.Filled.Image, contentDescription = "") },
            onClick = {
                scope.launch {
                    val result = snackbarHostState
                        .showSnackbar(
                            message = "스낵바 메세지",
                            actionLabel = "액션명",
                            // Defaults to SnackbarDuration.Short
                            duration = SnackbarDuration.Indefinite
                        )
                    when (result) {
                        SnackbarResult.ActionPerformed -> {
                            /* Handle snackbar action performed */
                        }
                        SnackbarResult.Dismissed -> {
                            /* Handle snackbar dismissed */
                        }
                    }
                }
            }
        )
    }
) { contentPadding ->
    // Screen content
}

 

 

Scaffold 없이 적용하는 경우

 

val snackBarState = remember { SnackbarHostState() }
val coroutineScope = rememberCoroutineScope()

Box(
    modifier = Modifier.fillMaxSize(),
    contentAlignment = Alignment.Center
) {

    Button(colors = ButtonDefaults.buttonColors(
        containerColor = Color.Blue,
        contentColor = Color.White
    ),
        onClick = {
            if (snackBarState.currentSnackbarData != null) {
                snackBarState.currentSnackbarData?.dismiss()
                return@Button
            }

            coroutineScope.launch {
                snackBarState.showSnackbar(
                    message = "스낵바 버튼명",
                    actionLabel = "액션명",
                    duration = SnackbarDuration.Short
                ).let {
                    when (it) {
                        SnackbarResult.ActionPerformed -> {
                            /* Handle snackbar action performed */
                        }

                        SnackbarResult.Dismissed -> {
                            /* Handle snackbar dismissed */
                        }
                    }
                }
            }
        }) {
        Text("스낵바 보이기")
    }

    SnackbarHost(hostState = snackBarState, modifier = Modifier.align(Alignment.BottomCenter))
}

 

위 방법들을 프로젝트 상황에 따라 적절하게 사용하시면 되겠습니다.

 

감사합니다.

 

728x90
반응형

관련글 더보기