Toast 訊息就像是很久以前的烤土司機一樣,會跳出簡短的文字訊息,以下示範如何使用。
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun MyApp() {
val context = LocalContext.current
val message = remember { mutableStateOf("") }
val keyboardController = LocalSoftwareKeyboardController.current
val focusManager = LocalFocusManager.current
Column(modifier = Modifier.fillMaxSize(),
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 = {
if(message.value.isNotEmpty())
Toast.makeText(context, message.value, Toast.LENGTH_SHORT).show() }
) {
Text(text = "點我蹦一則訊息")
}
}
}
簡單說明:keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done)
: 這是用於設置鍵盤選項的參數,imeAction = ImeAction.Done
表示軟鍵盤的 Enter 鍵顯示 “Done(完成)”或”勾勾”。keyboardActions = KeyboardActions(onDone = { ... })
: 當按下軟鍵盤的 Done(完成) 按鈕時,會執行以下。首先,keyboardController?.hide()
,表示要隱藏軟鍵。再來, focusManager.clearFocus()
則會使輸入框失去焦點,變成非被選取的狀態。
下面是展示畫面。
發佈留言