【问题标题】:How does setTextIsSelectable prevent the keyboard from appearing?setTextIsSelectable 如何防止键盘出现?
【发布时间】:2017-12-26 22:10:13
【问题描述】:

如果我创建一个包含单个 EditText 的单个 Activity 的简单应用程序,我会这样做

EditText editText = (EditText) findViewById(R.id.editText);
editText.setTextIsSelectable(true);

然后这会阻止键盘出现(在我对 Android 5.0 和 7.1 的测试中)。根据这些问题的要求,这就是我想要的:

source code

public void setTextIsSelectable(boolean selectable) {
    if (!selectable && mEditor == null) return; // false is default value with no edit data

    createEditorIfNeeded();
    if (mEditor.mTextIsSelectable == selectable) return;

    mEditor.mTextIsSelectable = selectable;
    setFocusableInTouchMode(selectable);
    setFocusable(selectable);
    setClickable(selectable);
    setLongClickable(selectable);

    // mInputType should already be EditorInfo.TYPE_NULL and mInput should be null

    setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null);
    setText(mText, selectable ? BufferType.SPANNABLE : BufferType.NORMAL);

    // Called by setText above, but safer in case of future code changes
    mEditor.prepareCursorControllers();
}

但我看不出这会导致输入法无法显示。

无论我是否设置setTextIsSelectable,调用以下方法都返回true

editText.isFocusable();             // true
editText.isFocusableInTouchMode();  // true
editText.isClickable();             // true
editText.isLongClickable();         // true

我之所以这么问,一方面是因为我很好奇,另一方面是因为我需要在我的应用中禁用系统键盘。我想了解正在发生的事情,以便我可以确定它确实在做我认为它正在做的事情。

更新

后续问答:

【问题讨论】:

  • @adneal,看来是因为!mTextView.isTextSelectable()。随意添加这个作为答案。我有点好奇为什么确保文本不可选择会成为显示键盘的决定因素(但回答我的问题不需要该信息)。

标签: android android-edittext textview android-softkeyboard


【解决方案1】:

当您调用TextView.setTextIsSelectable(true) 然后选择文本作为Editor.startSelectionActionModeInternal 的结果时,键盘不会显示,它会在显示文本选择ActionMode 之前检查TextView.isTextSelectable 是否为false

    final boolean selectionStarted = mTextActionMode != null;
    if (selectionStarted && !mTextView.isTextSelectable() && mShowSoftInputOnFocus) {
        // Show the IME to be able to replace text, except when selecting non editable text.
        final InputMethodManager imm = InputMethodManager.peekInstance();
        if (imm != null) {
            imm.showSoftInput(mTextView, 0, null);
        }
    }

我猜测为什么会以这种方式实现可能是因为框架团队决定他们想要文本Editor 可以预测可以选择不因为键盘移动而在屏幕上跳转。这可能只是一个 UI 决定。根据 git 的说法,自 2012 年以来一直是这样,但提交没有提及任何关于该实现的具体内容。

【讨论】:

    猜你喜欢
    • 2020-04-22
    • 2018-07-26
    • 2023-03-15
    • 2018-01-15
    • 1970-01-01
    • 2011-12-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多