在 Jetpack Compose 中打开键盘时处理后退按钮单击

问题描述 投票:0回答:1

下面提供的代码是我的问题的简化版本。

我想在键盘打开时单击设备后退按钮时触发操作。

当键盘关闭时,可以使用

BackHandler
处理后退按钮单击。但即使键盘打开我也想要它。

@Composable
fun BackHandlingWhenKeyboardOpen() {
    val focusManager = LocalFocusManager.current
    BackHandler(
        enabled = true,
    ) {
        // This is not triggered when keyboard is open
        Log.d("TEST_TAG", "Back Handler")
    }
    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier
            .fillMaxSize()
            .clickable(
                indication = null,
                interactionSource = remember { MutableInteractionSource() },
            ) {
                focusManager.clearFocus()
            }
    ) {
        TextField(
            value = "",
            onValueChange = {},
            keyboardActions = KeyboardActions(
                onDone = {
                    focusManager.clearFocus()
                },
            ),
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.NumberPassword,
                imeAction = ImeAction.Done,
            ),
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
        )
    }
}
android android-jetpack-compose back-button
1个回答
0
投票

尝试修改事件 onInterceptKeyBeforeSoftKeyboard

OutlinedTextField(
    value = "",
    onValueChange = { },
    label = { Text("Name") },
    keyboardOptions = KeyboardOptions.Default.copy(
        keyboardType = KeyboardType.NumberPassword,
        imeAction = ImeAction.Done,

        ),
    keyboardActions = KeyboardActions(
        onDone = {
            // handle value when keyboard done clicked
        }
    ),
    modifier = Modifier
        .fillMaxWidth()
        .onInterceptKeyBeforeSoftKeyboard { event ->
            if (event.key.nativeKeyCode == android.view.KeyEvent.KEYCODE_BACK) {
                // handle value when device back button clicked
                true

            } else {
                false

            }
        }
)
© www.soinside.com 2019 - 2024. All rights reserved.