在项目实战中加入了compose代码,在开发过程中遇到了不少问题,有两个控件目前感觉是很难用。
一个是Dialog 另一个是TextField ,先说TextField 使用这个自定义有些难,多次调整最终使用了BasicTextField,来完成自定义功能。代码如下:
@Composable
fun CustomTextField(
text: MutableState<String>,
modifier: Modifier = Modifier,
hint: String? = null,
onTextChange: String.() -> Unit = {},
leadingIcon: @Composable (() -> Unit)? = null,
trailingIcon: @Composable (() -> Unit)? = null,
keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
keyboardActions: String.() -> Unit = {},
textFieldStyle: TextStyle = LocalTextStyle.current,
hintTextStyle: TextStyle = LocalTextStyle.current,
) {
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically,
) {
leadingIcon?.invoke()
BasicTextField(
value = text.value,
onValueChange = { str ->
text.value = str
onTextChange.invoke(str)
},
cursorBrush = SolidColor(Co_333333),
singleLine = true,
modifier = Modifier
.weight(1f)
.padding(start = 15.dp),
textStyle = textFieldStyle,
decorationBox = { innerTextField ->
if (text.value.isBlank() && !hint.isNullOrBlank())
Box(
modifier = Modifier.fillMaxHeight(),
contentAlignment = Alignment.CenterStart
) {
innerTextField()
Text(
hint ?: "",
modifier = Modifier.fillMaxWidth(),
style = hintTextStyle,
)
} else innerTextField()
},
keyboardActions = KeyboardActions {
keyboardActions(text.value)
},
keyboardOptions = keyboardOptions
)
trailingIcon?.invoke()
}
}
另一个就是AlertDialog 和Dialog ,Dialog应该是比较基础的,AlertDialog是升级版本的dialog ,为了配合项目的UI,我使用了Dialog,但是在使用的时候感觉有一个bug,点击dialog按钮以外的地方 导致dialog卡死的问题,google也没发现别人出现这问题,估计现在使用的人数还很少,后续不知道会不会优化,没办法使用了Alert Dialog来自定义,问题又出现了,他的Text和title 是可以自定义内容的,可是自定义内容的高度有限制,导致对话框的内容不能正常填充,没办法我另辟蹊径,把title和Text都写成null,在buttons里面填充内容,完成了项目要求,说来也奇葩。代码如下:(请替换颜色代码)
@Composable
fun ShowCustomDialog(
showDialog: MutableState<Boolean>,
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
cancelText: String,
okText: String,
cancelOnClick: () -> Unit,
okOnClick: () -> Unit,
dismissOnClickOutside: Boolean = true,
dismissOnBackPress: Boolean = true,
) {
if (showDialog.value) {
AlertDialog(
modifier = modifier
.fillMaxWidth()
.background(color = Co_white, shape = RoundedCornerShape(9.dp)),
shape = RoundedCornerShape(9.dp),
properties = DialogProperties(
dismissOnClickOutside = dismissOnClickOutside,
dismissOnBackPress = dismissOnBackPress
),
onDismissRequest = {
showDialog.value = false
},
title = null,
text = null,
buttons = {
Column(modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()) {
content()
HorizontalDivider(color = Co_f5f5f5, height = 1.dp)
Row(modifier = Modifier.fillMaxWidth().height(50.dp)) {
TextButton(
modifier = Modifier
.weight(1f),
onClick = {
cancelOnClick.invoke()
showDialog.value = false
},
) {
Text(text = cancelText, color = Co_AAAAAA, fontSize = 16.sp)
}
Divider(
modifier = Modifier
.width(1.dp)
.fillMaxHeight(),
color = Co_f5f5f5
)
TextButton(
modifier = Modifier
.weight(1f),
onClick = {
okOnClick.invoke()
showDialog.value = false
},
) {
Text(okText, color = Co_FFFF772e, fontSize = 16.sp)
}
}
}
}
)
}
}