Android Compose 显示和隐藏键盘

4

我有一个使用 TextField 的可组合函数:

val focusManager = LocalFocusManager.current
TextField(
        keyboardOptions = KeyboardOptions.Default.copy(
            imeAction = ImeAction.Search,
        ),
        keyboardActions = KeyboardActions(
            onSearch = {
                focusManager.clearFocus()
            }
        )
    )

我需要在可组合函数内部和外部显示键盘,当我点击不属于可组合内容的其他按钮时,也需要显示键盘。基本上,我想从我的片段中调用hideKeyboard()

我尝试在可组合函数内部使用livedata:

val shouldShowKeyBoard by shouldShowSearchKeyBoard.observeAsState()

我可以通过focusManager.clearFocus()来隐藏键盘,但是我不确定如何以编程方式为特定的compose TextField显示它。

在compose中如何管理键盘的隐藏和显示?

3个回答

17
您可以在状态更改时执行一些操作,并且您可以使用“副作用”来实现它。例如,您可以使用LaunchedEffect函数,其中您可以将要监听的状态作为key传递。
LaunchedEffect(booleanValue) {
    //...do something
}
你可以使用ViewModel设置一个布尔值,类似于:
// initialize focus reference to be able to request focus programmatically
val focusRequester = remember { FocusRequester() }
LaunchedEffect(viewModel.showKeyboard) {
    focusRequester.requestFocus()
}

TextField(
    value = text,
    onValueChange = {
        text = it },
    modifier = Modifier
        // add focusRequester modifier
        .focusRequester(focusRequester)
)

注意:隐藏键盘的方法也可以是:

   val keyboardController = LocalSoftwareKeyboardController.current

   TextField(
     //...
     keyboardActions = KeyboardActions(
        onSearch = { keyboardController?.hide() }
    )
使用方法focusManager.clearFocus()来取消键盘并清除焦点。

工作解决方案,感谢@Gabriele的帮助。你能帮我解决这个问题吗:https://stackoverflow.com/questions/73650798/how-pass-parcelable-object-with-new-version-of-compose-navigation?noredirect=1#comment130059237_73650798 - InsaneCat

1
还有一个选项,可以在你自己的操作之后使用默认的键盘动作。我有一个搜索TextField,在点击“完成”后触发搜索功能,然后隐藏键盘。我通过在我的操作之后调用this.defaultKeyboardAction(ImeAction.Done)来实现隐藏键盘。
SearchTextField(
    textFieldState = searchState,
    placeholder = stringResource(R.string.common_search),
    keyboardActions = KeyboardActions(onDone = {
        onSearchDone()
        this.defaultKeyboardAction(ImeAction.Done) <-- This hides the keyboard
    })
)

使用搜索操作的话,应该是这样的:
SearchTextField(
    textFieldState = searchState,
    placeholder = stringResource(R.string.common_search),
    imeAction = ImeAction.Search,
    keyboardActions = KeyboardActions(onSearch = {
        onSearchDone()
        this.defaultKeyboardAction(ImeAction.Done)
    })
)

ImeAction.Search不会隐藏键盘,但完成操作会隐藏。

0

补充Gabriele的答案,你需要val focusRequester = remember { FocusRequester() },否则会抛出异常


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接