防止键盘出现在Jetpack Compose应用程序中

时间:2020-09-14 15:25:29

标签: android android-jetpack-compose

我正在制作用于学习Compose的计算器,因此我在屏幕上放置了自己的数字按钮,并希望防止出现软键盘。

这是我的仓库:https://github.com/vitor-ramos/CalculadorCompose

我注意到TextFieldImpl.kt中有一个修饰符来显示键盘,因此我尝试克隆代码并删除行:keyboardController.value?.showSoftwareKeyboard()我知道复制这样的代码不是一个好主意,但是我想尝试一下,但没有成功。正如您在下面的原始代码中看到的那样,有一个TODO表示应由BaseTextField处理,但我查看了它的代码,但没有发现它显示或隐藏键盘的位置。

val textFieldModifier = modifier
    .focusRequester(focusRequester)
    .focusObserver { isFocused = it.isFocused }
    .clickable(indication = null) {
        focusRequester.requestFocus()
        // TODO(b/163109449): Showing and hiding keyboard should be handled by BaseTextField.
        //  The requestFocus() call here should be enough to trigger the software keyboard.
        //  Investiate why this is needed here. If it is really needed, instead of doing
        //  this in the onClick callback, we should move this logic to the focusObserver
        //  so that it can show or hide the keyboard based on the focus state.
        keyboardController.value?.showSoftwareKeyboard()
    }

我在这个问题中发现,使用视图可以扩展EditText并更改功能,但是我没有找到Compose的等效项:Android: Disable soft keyboard at all EditTexts

public class NoImeEditText extends EditText {
    public NoImeEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    @Override
    public boolean onCheckIsTextEditor() {
        return false;
    }
}

1 个答案:

答案 0 :(得分:0)

使用 ReadonlyTextField 无法定位光标。所以在 compose AndroidView 中添加了包裹的 EditText

@Composable
fun NoKeyboardTextField(
    modifier: Modifier,
    text: String,
    textColor: Int
) {
    AndroidView(
        modifier = modifier,
        factory = { context ->
            AppCompatEditText(context).apply {
                isFocusable = true
                isFocusableInTouchMode = true
                showSoftInputOnFocus = false
            }
        },
        update = { view ->
            view.setText(text)
            view.setTextColor(textColor)
            view.setSelection(text.length)
        }
    )
}