第一次加载片段时,软件键盘不会出现

时间:2016-08-25 07:44:36

标签: android keyboard fragment

当加载片段(包括edittext)时,我一直在尝试自动显示键盘,并专注于编辑文本。

我尝试过使用:

     editTextPrice.requestFocus();
    InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imgr.showSoftInput(getView(), InputMethodManager.SHOW_IMPLICIT);

但是第一次加载片段时这不起作用。焦点已设置,我可以看到光标,但没有键盘出现。如果我关闭片段并再次添加它就可以了。

如果尝试从post()到使用处理程序将其推迟到onResume,等等。

有人知道可能导致这种情况发生的原因吗?

提前致谢。

祝你好运

4 个答案:

答案 0 :(得分:2)

让我解释一下为什么加载片段时键盘没有打开,视图无法获得焦点,因此我们需要在单独的线程中将焦点设置到视图,然后在打开keyBoard之后

void showKeyboard(Context mContext, View view)
{
    if (mContext != null && view != null && view.requestFocus())
    {
        InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }
}

以上功能是打开键盘

editTextPrice.postDelayed(() -> {
        editTextPrice.requestFocus();
    showKeyboard(getContext(), editTextPrice);
    }, 300);

答案 1 :(得分:0)

android:focusable="true"
android:focusableInTouchMode="true"

EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);

答案 2 :(得分:0)

您尝试使用以下2种功能:

   fun hideKeyBoard(context: Context, view: View) {
        val inputMethodManager = context.getSystemService(
            Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
    }

    fun showKeyBoard(context: Context, view: View) {
        val inputMethodManager = context.getSystemService(
            Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
    }

答案 3 :(得分:0)

不要从Java代码请求焦点。像

这样从xml本身进行操作
android:focusable="true" 

也在清单文件中执行以下操作

<activity android:name=".YourActivity"
    android:windowSoftInputMode="stateAlwaysVisible" />
相关问题