如何在使用setTextIsSelectable禁用键盘后启用键盘

时间:2017-07-21 03:34:20

标签: android android-edittext

我正在使用custom in-app keyboard,所以我需要禁用系统键盘。我可以用

做到这一点
editText.setShowSoftInputOnFocus(false);

适用于Android API 21+。但要做到同样的事情到API 11,我正在做

editText.setTextIsSelectable(true);

有时我想在使用setTextIsSelectable禁用系统键盘后再次显示系统键盘。但我无法弄清楚如何。执行以下操作会显示系统键盘,但如果用户隐藏键盘然后再次单击EditText,则键盘仍然无法显示。

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, 0);

我想我可以editText.setOnFocusChangeListener然后手动显示或隐藏系统键盘,但我更愿意撤消setTextIsSelectable所做的任何事情。以下也不起作用:

editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.setClickable(true);
editText.setLongClickable(true);

我该怎么做?

Related question

1 个答案:

答案 0 :(得分:2)

简短回答

执行以下操作将反转setTextIsSelectable(true)的效果并允许键盘在EditText获得焦点时再次显示。

editText.setTextIsSelectable(false);
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.setClickable(true);
editText.setLongClickable(true);
editText.setMovementMethod(ArrowKeyMovementMethod.getInstance());
editText.setText(editText.getText(), TextView.BufferType.SPANNABLE);

<强>解释

阻止键盘显示的内容是isTextSelectable()true。您可以看到here(感谢@adneal)。

setTextIsSelectable的源代码是

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();
}

因此,上面简短回答部分中的代码首先将mTextIsSelectable设置为false setTextIsSelectable(false),然后逐个撤消所有其他副作用。