基本觀念
TextField, OutlinedTextField, BasicTextField
都有相類似的功能,其差異如下:
TextField 和 OutlinedTextField 基本上功能相同,只是外觀不同
TextField 和 BasicTextField 很類似,只是 BasicTextField 少了設計外觀和部份功能,如果想要自己從頭打造外觀,就可以選 BasicTextField
必要參數
value 和 onValueChange 是必要的,而且要配合 remember 才能正常運作
value 是代表目前我們在 TextField 中輸入的值,我們通會會把他跟一個 state 連接
程式碼範例
@Composable
fun TextFieldDemo() {
var textFieldState by remember {
mutableStateOf("")
}
var outlineTextFieldState by remember {
mutableStateOf("")
}
Column(
modifier = Modifier
.padding(16.dp),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally,
){
TextField(
value = textFieldState,
onValueChange = {
textFieldState = it
},
textStyle = LocalTextStyle.current.copy(
textAlign = TextAlign.Right
),
label = {
Text("Name")
},
readOnly = false,
placeholder = {
Text("Enter you name")
},
leadingIcon = {
Icon(
imageVector = Icons.Outlined.MonitorHeart,
contentDescription = "Name"
)
},
trailingIcon = {
Icon(
imageVector = Icons.Outlined.Send,
contentDescription = "Send"
)
},
prefix = {
Text("$")
},
suffix = {
Text("Dollar")
},
supportingText = {
Text(text = "*required*")
},
isError = false,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Next
),
keyboardActions = KeyboardActions(
onNext = {
println("Keyboard done")
}
)
)
}
}
注意事項
如果要使用 by remember { } 要有以下的 import
import androidx.compose.runtime.remember // 通常會少以下 2 個,要記得補上 import androidx.compose.runtime.setValue import androidx.compose.runtime.getValue
不能直接在 composable function 中使用 coroutine,必須在 callback 中使用。
Never launch a coroutine directly in the composable, it’s only okay in callbacks such as an onClickListener
參考資料:
Android Dev: Compose 中的文字
Youtube: Stevdza – Text Fields – Jetpack Compose
(Philipp@YT): Text Fields – UX With Material3 (2023)
(Philipp@YT) Textfields, Buttons & Showing Snackbars – Android Jetpack Compose – Part 7 (2021)
Comments