Jetpack Compose,TextField 中的自定义光标位置

时间:2021-01-04 14:23:40

标签: android kotlin android-jetpack-compose

当它获得焦点时,如何将光标设置在 TextField 上的随机位置? 与经典 android 视图系统中的 editText.setSelection(position) 等效。

这是我用来让编辑文本在添加到屏幕时自动接收焦点的代码。 我希望能够从默认位置 0 移动光标

val (getText, setText) = remember { mutableStateOf("hello") }
AutofocusEditText(
    text = getText,
    setText = setText
)
    
...

@Composable
private fun AutofocusEditText(
    text: String,
    setText : (String) -> Unit
) {
    val focusState = remember { mutableStateOf(FocusState.Inactive) }
    val focusRequester = FocusRequester()
    val focusModifier = Modifier.focus()
    Row(
        modifier = Modifier.focusObserver { newFocusValue -> focusState.value = newFocusValue }
    ) {
        val focusRequesterModifier =
            Modifier.focusRequester(focusRequester)

        TextField(
            value = text,
            modifier = focusModifier.then(focusRequesterModifier),
            backgroundColor = Color.Transparent,
            onValueChange = setText,
            keyboardOptions = KeyboardOptions.Default.copy(
                imeAction = ImeAction.Done
            ),
            onImeActionPerformed = { action, softKeyboardController ->
                if (action == ImeAction.Done) {
                    softKeyboardController?.hideSoftwareKeyboard()
                }
            }
        )
    }
    onActive {
        focusRequester.requestFocus()
    }
}

1 个答案:

答案 0 :(得分:1)

您必须使用 TextField 的 TextFieldValue 版本。

@Composable
fun TextField(
    value: TextFieldValue,
    onValueChange: (TextFieldValue) -> Unit,
    /* ... */) {/* Impl */}

代码的简化版本:

    @Composable
    fun AutoFocusingText() {
        val textState = remember { mutableStateOf(TextFieldValue()) }
        val focusState = remember { mutableStateOf(FocusState.Inactive) }
        val focusRequester = FocusRequester()
        val focusModifier = Modifier.focus()
        Row(
            modifier = Modifier.focusObserver { focusState.value = it }
        ) {
            val focusRequesterModifier = Modifier.focusRequester(focusRequester)
            TextField(
                modifier = focusModifier.then(focusRequesterModifier),
                value = textState.value,
                onValueChange = { value: TextFieldValue ->
                    textState.value = value
                }
            )
        }
        onActive {
            focusRequester.requestFocus()
        }
    }

如果您有一个非空字符串作为初始值,您必须手动更改选择。将空的 TextFieldValue 替换为:TextFieldValue(text = value, selection = TextRange(value.length, value.length))

当您想提取代码中的值时。您可以将当前选择添加为参数,或者将其与 TextFieldValue 结合提取。否则,如果用户在文本中间进行编辑,则光标会在下一个 onValueChanged 时跳回到末尾。