当EditText获得焦点时,强制显示软键盘

13

我有一个EditText,我正在通过编程将焦点传递给它。但是当我这样做时,我希望键盘也出现(并在该EditText失去焦点时关闭)。目前,用户必须单击EditText才能使键盘显示 - 即使EditText已经获得了焦点。

5个回答

23
<activity   android:name=".YourActivity"
            android:windowSoftInputMode="stateVisible" />

将此添加到清单文件中...


这个可以工作,谢谢。在我的情况下,一个活动在打开时获得焦点(上面的配置不在清单文件中)。另一个具有相同代码和设计的活动直到我将此添加到清单之前才会出现:/。我不明白为什么会这样奇怪。 - Günay Gültekin

20

这是我展示键盘的方式:

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

10
这真的有效。但是,你必须先通过 requestFocus() 方法获取到 EditText 的焦点,然后再打开键盘。反过来是行不通的。 - gaborsch
1
感谢@GaborSch的评论,加一。 - Chirag Savsani

7

在你的清单文件中为你的活动设置这个属性,以便在屏幕上包含EditText框时自动弹出键盘。

<activity android:windowSoftInputMode="stateAlwaysVisible" ... />

要在失去焦点时隐藏键盘,请为EditText设置OnFocusChangeListener。

在onCreate()方法中:

EditText editText = (EditText) findViewById(R.id.textbox);
OnFocusChangeListener ofcListener = new MyFocusChangeListener();
editText.setOnFocusChangeListener(ofcListener);

添加这个类

private class MyFocusChangeListener implements OnFocusChangeListener {

    public void onFocusChange(View v, boolean hasFocus){

        if(v.getId() == R.id.textbox && !hasFocus) {

            InputMethodManager imm =  (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

        }
    }
}

6
展示键盘,请使用以下代码。
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);

使用以下代码隐藏键盘,其中et是EditText的引用。

InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(et.getWindowToken(), 0);

0

如果你想基于焦点监听器来实现它,你应该选择:

final InputMethodManager imm =(InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
editText.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus){
                imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
            }else{
                 imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
            }
            imm.toggleSoftInput(0, 0);
        }
    });

希望这能有所帮助。
祝好!

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