附上查看视频剪辑,下面是工作代码,请导入必要的库
点击第二个文本字段正在使用初始状态值重置第一个文本字段值
将视频上传到 YouTube 上作为未列出,请检查。
新来编写 UI,抱歉,如果这是一个基本问题
@Composable
fun SignupScreen() {
Log.d("Recomposition", "SignupScreen is recomposing")
Scaffold { innerPadding ->
val nameTextField by rememberSaveable {
mutableStateOf("reset 1")
}
val emailTextField by rememberSaveable {
mutableStateOf("reset 2")
}
Column(
Modifier
.padding(innerPadding)
.onGloballyPositioned {
Log.d("Recomposition", "MyComposable layout changed")
}
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
CustomTextField(textFieldValue = nameTextField, label = "Your name") { value ->
val returnValue: String? = if (value.length < 5) {
"Name is short"
} else {
null
}
returnValue
}
CustomTextField(textFieldValue = emailTextField, label = "Your email") { value ->
val emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$".toRegex()
val returnValue: String? = if (emailRegex.matches(value)) {
null
} else {
"invalid email address"
}
returnValue
}
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun CustomTextField(
modifier: Modifier = Modifier,
textFieldValue: String,
label: String,
validator: ((String) -> String?)? = null
) {
Log.d("Recomposition", "MyComposable is recomposing")
var errorString by rememberSaveable {
mutableStateOf<String?>(null)
}
BasicTextField2(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 10.dp),
value = textFieldValue,
onValueChange = { value ->
validator?.let {
errorString = validator(value)
}
},
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
textStyle = TextStyle(fontSize = 18.sp),
decorator = { innerTextField ->
Column {
Text(
text = label,
color = if (errorString == null) Color.Black else Color.Red,
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.height(10.dp))
innerTextField()
Spacer(modifier = Modifier.height(7.dp))
HorizontalDivider(color = if (errorString == null) DividerDefaults.color else Color.Red)
if (errorString != null) {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(end = 5.dp),
text = errorString!!,
color = Color.Red,
fontSize = 13.sp,
textAlign = TextAlign.End
)
}
}
}
)
}
忽略这个。添加几句话只是为了避免描述较少导致库存溢出错误
我正在回答我的问题,有一些想法
保存 onValueChanged 回调中的值后,点击其他文本字段时,文本字段状态不会重置,
对于其他文本字段,onValueChanged 是强制性的,但对于 BasicTextField2 不是强制性的,而且 BasicTextField2 更新其 UI 时无需 onValueChanged 回调 -> 它往往这样做以提高性能,但当我们点击其他文本字段时,它会保留该值,因为它只能容纳一个文本值实例
我不确定我的解释是否正确。如果我错了请纠正我