Ind*_*ana 5 android android-jetpack-compose
我遇到一个问题,当文本字段接收焦点时,软键盘在类型之间闪烁。
我有一个TextField想要输入数字的地方,但是当接收View焦点时,软键盘会在标准文本键盘和数字键盘之间滑动。
我创建了一个快速 gif 来演示:

我怀疑在重组发生时我做错了什么,但我看不出哪里可能导致这种情况。
下面是演示实现的代码:
@Composable
fun PinInput(focusManager: FocusManager) {
Card(
modifier = Modifier.size(60.dp, 80.dp),
elevation = 0.dp,
backgroundColor = ColorSurface,
border = BorderStroke(2.dp, ColorLightBorder)
) {
EditableInput(
textStyle = Typography.h1.copy(
textAlign = TextAlign.Center,
fontSize = Dimens.TextSizeGiant
),
onTextChange = { value ->
if (value.isNotEmpty()) focusManager.moveFocus(Right)
else focusManager.moveFocus(Left)
},
maxLength = 1,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.NumberPassword,
imeAction = ImeAction.Next
),
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(Right) })
)
}
}
Run Code Online (Sandbox Code Playgroud)
@Composable
fun EditableInput(
state: EditableInputState = rememberEditableInputState(),
textStyle: TextStyle = Typography.body1.copy(textAlign = TextAlign.End),
onTextChange: (String) -> Unit = {},
keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
keyboardActions: KeyboardActions = KeyboardActions(),
maxLength: Int = NO_VALUE
) {
TextField(
modifier = Modifier.fillMaxWidth(),
colors = TextFieldDefaults.textFieldColors(
textColor = ColorOnSurface,
backgroundColor = ColorSurface,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent
),
textStyle = textStyle,
singleLine = true,
value = state.text,
onValueChange = { value ->
if (maxLength == NO_VALUE || (maxLength != NO_VALUE && value.length <= maxLength)) {
state.text = value
onTextChange(value)
}
},
placeholder = { Text(text = state.hint) },
keyboardOptions = keyboardOptions,
keyboardActions = keyboardActions
)
}
Run Code Online (Sandbox Code Playgroud)
@Composable
fun rememberEditableInputState(hint: String = ""): EditableInputState =
rememberSaveable(hint, saver = EditableInputState.SAVER) { EditableInputState(hint, hint) }
class EditableInputState(val hint: String, initialText: String) {
var text by mutableStateOf(initialText)
val isHint: Boolean
get() = text == hint
companion object {
val SAVER: Saver<EditableInputState, *> = listSaver(
save = { listOf(it.hint, it.text) },
restore = { EditableInputState(it[0], it[1]) }
)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
804 次 |
| 最近记录: |