【问题标题】:Jetpack compose listener for keyboard actions (setOnKeyListener) (Textfield for SMS)Jetpack 为键盘操作编写侦听器(setOnKeyListener)(SMS 的文本字段)
【发布时间】:2021-07-31 21:33:11
【问题描述】:

我有五个文本字段。在第一个字段中输入内容后,焦点移动到下一个文本字段。 如果我在文本字段中删除了某些内容 - 焦点会移动到之前的文本字段。 所有重点工作都通过 onValueChanged 部分

但是如果文本字段中的值空白(“”) - 如果我在键盘上按退格键,onValueChanged 没有任何反应,因为字段中的值没有改变。而且我需要以某种方式将注意力集中在以前的文本字段上

那么我如何在撰写中的文本字段的软键盘中使用侦听器进行后按?

我尝试使用 KeyboardActions,

keyboardActions = KeyboardActions(
                    onPrevious = {
                        //some work with foucs
                    },
                ),

但它不起作用

第二个问题: 如果文本字段被点击(或获得焦点)如何在结束文本的字段中设置光标?
即使用户单击末尾的字符串光标集的中间,我也需要。

【问题讨论】:

  • 你可以使用Modifier.onKeyEvent
  • 我用我的解决方案创建了这个要点:gist.github.com/nglauber/312052d2989aff50b9331aa6e0f816f7 它部分工作,但由于某种原因,当焦点改变时键盘类型会迅速改变......也许我们可以合并我们的解决方案:)跨度>
  • @nglauber 喜欢你的解决方案,它比我的好得多。有一些小的改动: 1. 全部在 onValueChange 中: if (it.isDigitsOnly()) {code} 只取数字。 2. 如果已经有,则重写新数字:``` if (it.length > 1) { digits[i] = it.last().toString() return@TextField } ``
  • 3.如果在文本字段中已经有了一些东西 - 接下来移动焦点(在 .onKeyEvent 中)``` else if (digits[i] != "") { focus[i+1].requestFocus() } ```

标签: android kotlin textfield event-listener android-jetpack-compose


【解决方案1】:

使用解决方案@nglauber 用于输入短信的文本字段(暂时):

@Composable
fun SMSTextFields(
    modifier: Modifier,
    smsCodeLength: Int = 5,
    whenFull: (smsCode: String) -> Unit
) {
    val enteredNumbers = remember {
        mutableStateListOf(
            *((0 until smsCodeLength).map { "" }.toTypedArray())
        )
    }
    val focusRequesters: List<FocusRequester> = remember {
        (0 until smsCodeLength).map { FocusRequester() }
    }
    Row(modifier = modifier.padding(start = 60.dp, end = 60.dp)) {
        (0 until smsCodeLength).forEach { index ->
            TextField(
                modifier = Modifier
                    .weight(1f)
                    .size(120.dp, 80.dp)
                    .onKeyEvent { event ->
                        val cellValue = enteredNumbers[index]
                        if (event.type == KeyEventType.KeyUp) {
                            if (event.key == Key.Backspace && cellValue == "") {
                                focusRequesters
                                    .getOrNull(index - 1)
                                    ?.requestFocus()
                                enteredNumbers[index - 1] = ""
                            } else if (cellValue != "") {
                                focusRequesters
                                    .getOrNull(index + 1)
                                    ?.requestFocus()
                            }
                        }
                        false
                    }
                    .padding(vertical = 2.dp)
                    .focusOrder(focusRequesters[index])
                    .focusRequester(focusRequesters[index]),
                colors = TextFieldDefaults.textFieldColors(
                    backgroundColor = whiteBackground,
                    unfocusedIndicatorColor = greyColor,
                    focusedIndicatorColor = signUpColorButton,
                    cursorColor = greyColor,
                    textColor = greyColor
                ),
                textStyle = smsCodeEnterStyle,
                singleLine = true,
                value = enteredNumbers[index],
                onValueChange = { value: String ->
                    if (value.isDigitsOnly()) {
                        if (value.length > 1) {
                            enteredNumbers[index]  = value.last().toString()
                            return@TextField
                        }
                        if (focusRequesters[index].freeFocus()) {
                            enteredNumbers[index] = value
                            if (enteredNumbers[index].isBlank() && index > 0 && index <5) {
                                focusRequesters[index - 1].requestFocus()
                            } else if (index < smsCodeLength - 1) {
                                focusRequesters[index + 1].requestFocus()
                            }
                            else if (enteredNumbers.size == 5){
                                whenFull(enteredNumbers.joinToString(separator = ""))
                            }
                        }
                    }
                },
                keyboardOptions = KeyboardOptions.Default.copy(
                    keyboardType = KeyboardType.Number,
                    imeAction = ImeAction.Next
                ),
            )
            Spacer(modifier = Modifier.width(4.dp))
        }
    }
}

【讨论】:

  • 使用这两种解决方案时,当焦点改变时,我仍然遇到键盘问题...我为此打开了一个勾号...issuetracker.google.com/issues/187746439
  • @nglauber,是的,我也有同样的问题
  • 我创建了一篇文章,解释了该问题的可能解决方法,您也可以在此处使用相同的方法,希望对您有所帮助。 chetangupta.net/keyboard-switch-bug
【解决方案2】:
@ExperimentalComposeUiApi
@Composable
fun EnterOtpView() {
    val scrollState = rememberScrollState()
    val focusManager = LocalFocusManager.current
    val digits = remember {
        mutableStateListOf(
            *((0 until 4).map { "" }.toTypedArray())
        )
    }
    val focusRequesters: List<FocusRequester> = remember {
        (0 until 4).map { FocusRequester() }
    }
    Column(
        Modifier.padding(horizontal = 70.dp),  
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.CenterHorizontally,

        ) {
        Text(
            text = "123 456 8550", style = MaterialTheme.typography.h3, color = Purple,
            modifier = Modifier.padding(top = 20.dp, bottom = 30.dp)
        )
        Row(
            modifier = Modifier
                .fillMaxWidth(1f)
                .wrapContentHeight(),
            Arrangement.SpaceBetween,
            Alignment.CenterVertically
        ) {
            (0 until 4).forEach { index ->
                TextField(
                    modifier = Modifier
                        .weight(0.2f)
                        .padding(end = 4.dp)
                        .onKeyEvent {
                            if (it.nativeKeyEvent.keyCode == 67) {
                                if (digits[index].isEmpty()) {
                                    focusManager.moveFocus(FocusDirection.Left)
                                }
                                digits[index] = ""
                            }
                            true
                        }
                        .padding(vertical = 2.dp)
                        .focusOrder(focusRequesters[index])
                        .focusRequester(focusRequesters[index]),
                    colors = TextFieldDefaults.textFieldColors(
                        backgroundColor = Color.Transparent
                    ),
                    singleLine = true,
                    textStyle = MaterialTheme.typography.body1.copy(textAlign = TextAlign.Center),
                    value = digits[index],
                    onValueChange = {
                        if (digits[index].isEmpty() && it.isDigitsOnly()) {
                            digits[index] = it
                            focusManager.moveFocus(FocusDirection.Right)
                        }
                    },
                    keyboardOptions = KeyboardOptions(
                        imeAction = ImeAction.Next,
                        keyboardType = KeyboardType.Number
                    ),
                    keyboardActions = KeyboardActions(
                        onNext = {
                            focusManager.moveFocus(FocusDirection.Right)
                        }
                    )
                )
            }
        }
}}

使用 nativeKeyEvent 和 focusManager 为我工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 2013-09-10
    • 1970-01-01
    • 2016-05-16
    相关资源
    最近更新 更多