Jetpack Compose 中 BasicTextField 的焦点有多清晰?

时间:2021-04-12 12:45:17

标签: android kotlin android-jetpack android-jetpack-compose

我有一个 Jetpack Compose (Beta04) BasicTextField(带装饰框)。如何清除焦点?

我尝试过使用 focusRequester 但这不起作用:

val focusRequester = remember { FocusRequester() }

// ...

BasicTextField(modifier = Modifier.focusRequester(focusRequester), /* ... */)

// ...

placesFocusRequester.freeFocus()

1 个答案:

答案 0 :(得分:9)

要从当前聚焦的组件中清除焦点,您可以使用 FocusManager.clearFocus 方法:

    val focusRequester = remember { FocusRequester() }
    val focusManager = LocalFocusManager.current
    var value by rememberSaveable { mutableStateOf("initial value") }
    BasicTextField(
        value = value,
        onValueChange = { value = it },
        decorationBox = { innerTextField ->
            Row(
                Modifier
                    .background(Color.LightGray, RoundedCornerShape(percent = 30))
                    .padding(16.dp)
                    .focusRequester(focusRequester)
            ) {
                //...
                innerTextField()
            }
        }
    )
  
    Button(onClick = { focusManager.clearFocus() }) {
        Text("Clear focus")
    }