我想在EditText被聚焦时自动显示软键盘(如果设备没有物理键盘),我有两个问题:

当我的活动显示时,我的EditText是集中的,但键盘不显示,我需要再次单击它来显示键盘(它应该显示时,我的活动显示)。 当我在键盘上点击完成时,键盘被解散,但EditText保持集中,我不想(因为我的编辑已经完成)。

继续说,我的问题是有一些更像iPhone的东西:保持键盘与我的EditText状态同步(聚焦/不聚焦),当然,如果有物理键盘,也不会呈现软键盘。


当前回答

没有一个答案对我有用。这里有一个简单的方法。

searchEditText.setVisibility(View.VISIBLE);
                final Handler handler=new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        searchEditText.requestFocus();
                    }
                }, 400);

只是将requestFocus()方法延迟了400ms。

其他回答

对于Kotlin,只需使用以下扩展:

fun EditText.showKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

fun EditText.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(this.windowToken, 0)
}

在onCrete() activity()方法的editText上调用requestFocus()方法,并在相同的editText上调用clearFocus()方法,当在键盘上单击完成。

要使键盘出现,请使用

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

这个方法比直接调用InputMethodManager更可靠。

要关闭它,使用

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

芬兰湾的科特林:

val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

fun showKeyboard() {
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
    }

fun hideKeyboard() {
        imm.hideSoftInputFromWindow(phoneNoInputTxt.windowToken, 0);
    }

那你想怎么叫就怎么叫!

我用定时器。键盘可以显示编辑文本聚焦。

    edittext = (EditText) findViewById(R.id.edittext );
    edittext.requestFocus();
    edittext.setFocusableInTouchMode(true);
    if (edittext.requestFocus()) {
        final Thread timer = new Thread() {
            public void run() {
                try{
                    sleep(500);
                    InputMethodManager imm =(InputMethodManager) getApplicationContext().getSystemService(INPUT_METHOD_SERVICE);
                    imm.showSoftInput(edittext, SHOW_IMPLICIT);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        timer.start();