当EditText获得焦点时如何显示软键盘?

4

我的活动中有三个EditText视图,它们会在某些时候随机隐藏
在EditText中输入单个文本后,软键盘将自动消失
现在我想在EditText获得焦点时显示软键盘
怎么做呢?
提前致谢

2个回答

2

通过使用InputMethodManager,您可以显示和隐藏软键盘。当EditText获得焦点时,使用toggleSoftInput()方法显示软键盘,并使用hideSoftInputFromWindow()EditText失去焦点时隐藏键盘,如下所示...

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean isFocused) {

        if (isFocused) {

            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        } else {

            imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0); 
        }
    }
});

1
请尝试使用以下代码...
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
    inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接