【Jetpack Compose 筆記】Snackbar 點心條訊息

直接來上菜(來點扣的吧)。

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun MyApp() {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val snackbarHostState = remember { SnackbarHostState() }
    val message = remember { mutableStateOf("") }
    val keyboardController = LocalSoftwareKeyboardController.current
    val focusManager = LocalFocusManager.current

    Scaffold(
        snackbarHost = {SnackbarHost(hostState = snackbarHostState)}
    ) { contentPaddingValues ->
        Column(modifier = Modifier.fillMaxSize().padding(contentPaddingValues),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center) {
            TextField(
                value = message.value,
                onValueChange = {
                    message.value = it
                },
                label = {Text("輸入你想丟出的點心條訊息?")},
                maxLines = 1,
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
                keyboardActions = KeyboardActions(
                    onDone = {
                        keyboardController?.hide()
                        focusManager.clearFocus()
                    }
                )
            )

            Button(
                onClick = {
                    keyboardController?.hide()
                    focusManager.clearFocus()
                    if(message.value.isNotEmpty()){
                        scope.launch {
                            val result = snackbarHostState.showSnackbar(
                                message = message.value,
                                actionLabel = "我瞭了啦",
                                withDismissAction = true)
                            when(result){
                                SnackbarResult.ActionPerformed ->{
                                    Toast.makeText(context,"我就知道你瞭了", Toast.LENGTH_SHORT).show()
                                }
                                SnackbarResult.Dismissed -> {
                                    Toast.makeText(context,"好啦好啦~ 別這麼兇啦", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    }
                }
            ) {
                Text(text = "點我丟出一則訊息")
            }
        }
    }

    
}

示範畫面:

簡單說明:

Snackbar 不像 Toast 需要程式的 Context

  1. 不過它需要放在 Scaffold 裡面的 snackbarHost = {SnackbarHost(hostState = snackbarHostState)},所以宣告的地方有變數 val snackbarHostState = remember { SnackbarHostState() }
  2. 使用時需要透過協程 ( CoroutineSope )呼叫,所以有 val scope = rememberCoroutineScope() 的變數宣告,與 scope.launch {snackbarHostState.showSnackbar(message ="....."} 的使用方法。

參考資料: https://developer.android.com/jetpack/compose/components/snackbar?hl=zh-tw


留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *