如何在关注edittext时显示软键盘

Lud*_*dry 422 keyboard android focus android-softkeyboard android-edittext

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

  1. 当我Activity显示时,我EditText的注意力集中但键盘没有显示,我需要再次点击它来显示键盘(显示我的键盘时应Activity显示).

  2. 当我在键盘上单击完成时,键盘被解除但是EditText保持聚焦并且不想要(因为我的编辑完成了).

要恢复,我的问题是在iPhone上有更多类似的东西:它使键盘与我的EditText状态同步(聚焦/不聚焦),当然如果有物理键盘,则不会出现软键盘.

rau*_*aug 576

要强制显示软键盘,您可以使用

EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
Run Code Online (Sandbox Code Playgroud)

为了消除焦点EditText,遗憾的是你需要一个假人View来抓住焦点.

我希望这有帮助


要关闭它你可以使用

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
Run Code Online (Sandbox Code Playgroud)

这适用于在对话框中使用它

public void showKeyboard(){
    InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

public void closeKeyboard(){
    InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
Run Code Online (Sandbox Code Playgroud)

  • 在具有焦点的对话框中使用EditText对我不起作用.不知道为什么. (154认同)
  • 只能与```yourEditText.requestFocus()``一起使用,如下所述:http://stackoverflow.com/questions/8991522/how-can-i-set-the-focus-and-display-the-键盘上 - 我 - 的EditText程序化 (22认同)
  • @AbdellahBenhammou,在你的DialogFragment的onCreate()中执行此操作:getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); (18认同)
  • @AbdellahBenhammou,可能在显示软输入之前在编辑文本上执行requestFocus调用可能会解决您的问题.它对我有用. (10认同)
  • 2021年我仍然遇到这个问题,这可能是整个框架中最烦人的问题 (3认同)
  • 如果我这样做,当活动出现时显示软键盘(这很好),但是当我的焦点离开EditText并转到按钮时,键盘保持不变(这很糟糕). (2认同)
  • 完整的n00b问题:带有物理键盘的设备会发生什么,是否也显示了软键盘? (2认同)
  • 我通过这样的编码让软键盘出现在弹出窗口中 AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); AlertDialog alert = alertDialog.show(); alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); (2认同)
  • 只有当我在`postDelayed`处理程序中包装`requestFocus()`/`showSoftInput()`时,这对我有用,就像在另一个顶级答案中一样.这是在Android 6.0上,支持lib`EditText`. (2认同)
  • 直到我将代码从“onCreateView”移动到“onViewCreated”后,这才起作用。如果它在`onCreateView`中,您需要延迟执行`showSoftInput` (2认同)

Mik*_*nov 221

我有同样的问题.在editText VISIBILITY从GONE更改为VISIBLE之后,我不得不设置焦点并显示软键盘.我使用以下代码实现了这一点:

new Handler().postDelayed(new Runnable() {

    public void run() {
//        ((EditText) findViewById(R.id.et_find)).requestFocus();
//              
        EditText yourEditText= (EditText) findViewById(R.id.et_find);
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);

        yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
        yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));                           
    }
}, 200);
Run Code Online (Sandbox Code Playgroud)

它对我有100ms的延迟,但没有任何延迟或只有1ms的延迟失败.

代码的注释部分显示了另一种方法,该方法仅适用于某些设备.我在OS 2.2版(仿真器),2.2.1(真实设备)和1.6(仿真器)上进行了测试.

这种方法给我带来了很多痛苦.

  • 我不知道有什么东西可以同时如此丑陋和如此美丽.非常感谢! (46认同)
  • @jellyfish这模拟了对`EditText`的点击.对于读这个的人来说,你也可以在`yourEditText`小部件上使用`View.postDelayed()`方法,而不是创建一个新的`Handler`. (14认同)
  • 这是一个黑客 - 大卫钱德勒更好的解决方案. (5认同)
  • 如果David Chandler的解决方案适用于所有Android版本/设备,并且VISIBILITY刚刚从GONE更改为VISIBLE,那么YES - 您应该使用他的解决方案. (4认同)
  • 同意.你知道更好的解决方案适用于所有Android风格吗? (3认同)
  • 这是天才,迈克.也许是一个扭曲的天才,但"对我有用". (2认同)
  • 完美的!即使没有延迟发布,也可以在 DialogFragment 中为我工作。+1 (2认同)

Dav*_*ler 155

要使键盘出现,请使用

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
Run Code Online (Sandbox Code Playgroud)

此方法比直接调用InputMethodManager更可靠.

要关闭它,请使用

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Run Code Online (Sandbox Code Playgroud)

  • 有人可以解释为什么这比直接调用`InputMethodManager`更可靠吗?(例如,与raukodraug的解决方案不同,它不起作用.) (12认同)
  • 对我也不起作用.在Android 2.3.5中工作.raukodraug的解决方案对我有用.搜索版本依赖但无法找到. (5认同)
  • 这在Android 4.4.2中适用于我.选择作为此帖的解决方案的InputMethodManager方法对我不起作用. (2认同)
  • 在Android 4.4.2中不适用于我。它显示了键盘,但没有隐藏它。 (2认同)

Bol*_*ing 80

没有其他工作,强制显示:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
Run Code Online (Sandbox Code Playgroud)

  • 你是对的,@ Bolling!没有其他工作,你的代码救了我.谢谢! (4认同)
  • 你的代码是唯一一个为我工作的代码,我在这个页面上尝试了每个解决方案!非常感谢! (3认同)
  • 不要强迫它.在某些情况下,当你从前台移动到背景时,键盘将保留在那里,因为你强迫它.这是一个碎片问题,但我已经在三星二重奏中看到了它. (3认同)

Rob*_*ies 72

以下代码是从Google 4.1的SearchView源代码中掠夺的.似乎工作,在较小版本的Android上也很好.

private Runnable mShowImeRunnable = new Runnable() {
    public void run() {
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm != null) {
            imm.showSoftInput(editText, 0);
        }
    }
};

private void setImeVisibility(final boolean visible) {
    if (visible) {
        post(mShowImeRunnable);
    } else {
        removeCallbacks(mShowImeRunnable);
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindowToken(), 0);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在创建Control/Activity时,需要添加以下代码.(在我的例子中,它是一个复合控件,而不是一个活动).

this.editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    public void onFocusChange(View v, boolean hasFocus) {
        setImeVisibility(hasFocus);
    }
});
Run Code Online (Sandbox Code Playgroud)

  • :-D`setImeVisibility(hasFocus)`? (37认同)
  • 在尝试了几种变体之后,这是唯一一种对我始终有效的变体(Android 4.42)。谢谢 (2认同)

小智 31

android:windowSoftInputMode="stateAlwaysVisible" - >在清单文件中.

edittext.requestFocus(); - >代码.

这将打开软键盘,当活动出现时,编辑文本具有请求焦点.

  • 这将在Activity创建时打开键盘. (2认同)

小智 29

我在最近的一些简单案例中运用了下面的代码.我还没有完成所有测试,但....

EditText input = (EditText) findViewById(R.id.Input);
input.requestFocus();    
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
Run Code Online (Sandbox Code Playgroud)

然后键盘出现了.


Vad*_*4uk 14

您可以尝试强制显示软键盘,它适用于我:

...
dialog.show();
input.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
Run Code Online (Sandbox Code Playgroud)


Xie*_*eyi 9

有时raukodraug的答案是行不通的.我通过这种方式进行了一些试验和错误:

public static void showKeyboard(Activity activity) {
    if (activity != null) {
        activity.getWindow()
                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}

public static void hideKeyboard(Activity activity) {
    if (activity != null) {
        activity.getWindow()
                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
}
Run Code Online (Sandbox Code Playgroud)

EditText部分:

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                hideKeyboard(getActivity());
            } else {
                showKeyboard(getActivity());
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)


Mub*_*har 9

要隐藏键盘,请使用以下键盘:

getActivity().getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Run Code Online (Sandbox Code Playgroud)

并显示键盘:

getActivity().getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Run Code Online (Sandbox Code Playgroud)


Ste*_*mau 8

这是我从Square获得的更可靠的解决方案:

\n

\r\n
\r\n
fun View.focusAndShowKeyboard() {\n   /**\n    * This is to be called when the window already has focus.\n    */\n   fun View.showTheKeyboardNow() {\n       if (isFocused) {\n           post {\n               // We still post the call, just in case we are being notified of the windows focus\n               // but InputMethodManager didn\'t get properly setup yet.\n               val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager\n               imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)\n           }\n       }\n   }\n\n   requestFocus()\n   if (hasWindowFocus()) {\n       // No need to wait for the window to get focus.\n       showTheKeyboardNow()\n   } else {\n       // We need to wait until the window gets focus.\n       viewTreeObserver.addOnWindowFocusChangeListener(\n           object : ViewTreeObserver.OnWindowFocusChangeListener {\n               override fun onWindowFocusChanged(hasFocus: Boolean) {\n                   // This notification will arrive just before the InputMethodManager gets set up.\n                   if (hasFocus) {\n                       this@focusAndShowKeyboard.showTheKeyboardNow()\n                       // It\xe2\x80\x99s very important to remove this listener once we are done.\n                       viewTreeObserver.removeOnWindowFocusChangeListener(this)\n                   }\n               }\n           })\n   }\n}
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

代码积分来自这里

\n


Ale*_*sel 7

Kotlin 用于在焦点上显示键盘的扩展。

这是之前回复的组合,其中要么太长要么不完整。

此扩展在消息队列上发布一个 runnable,在请求焦点后显示软键盘:

fun View.showSoftKeyboard() {
    post {
        if (this.requestFocus()) {
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

之后需要时从任何视图调用它:

editText.showSoftKeyboard()
Run Code Online (Sandbox Code Playgroud)


vin*_*odi 6

showSoftInput 根本不适合我.

我想我需要设置输入模式:(此处在清单中的Activity组件中)

android:windowSoftInputMode="stateVisible" 
Run Code Online (Sandbox Code Playgroud)


Tar*_*Ray 6

它对我有用。您也可以尝试使用此方法来显示键盘:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
Run Code Online (Sandbox Code Playgroud)


Ari*_*han 6

对于片段,确定它的工作:

 displayName = (EditText) view.findViewById(R.id.displayName);
    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
Run Code Online (Sandbox Code Playgroud)


Wal*_*ann 6

只需在 EditText 视图中添加这一行:

android:isScrollContainer="true"
Run Code Online (Sandbox Code Playgroud)

和 TADA - 键盘开始自动出现!

我遇到了类似的问题,并发现了这个简单而奇怪的解决方案。

正如 user3392439 在这里提到的,焦点上的键盘外观与 XML 文件中滚动组件的存在有某种奇怪的联系。

即使在同一 XML 中包含上述行的另一个EditText 视图的存在也会使键盘出现,无论当前关注哪个 EditTexts。

如果您的 XML 文件中至少有一个包含滚动组件的可见视图 - 键盘将自动出现在焦点上。

如果没有滚动 - 那么您需要单击 EditText 以显示键盘。


小智 5

相信与否,当我发现“活动”动画可以禁用“软键盘”时,解决了我的“软键盘”问题。当您用

i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
Run Code Online (Sandbox Code Playgroud)

overridePendingTransition(0, 0);
Run Code Online (Sandbox Code Playgroud)

它可以隐藏软键盘,并且无法显示它。


小智 5

我在各种不同情况下都遇到了相同的问题,在某些情况下我发现了解决方案,但在另一些情况下却不起作用,因此,这里的组合解决方案在我发现的大多数情况下都有效:

public static void showVirtualKeyboard(Context context, final View view) {
    if (context != null) {
        final InputMethodManager imm =  (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        view.clearFocus();

        if(view.isShown()) {
            imm.showSoftInput(view, 0);
            view.requestFocus();
        } else {
            view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
                @Override
                public void onViewAttachedToWindow(View v) {
                    view.post(new Runnable() {
                        @Override
                        public void run() {
                            view.requestFocus();
                            imm.showSoftInput(view, 0);
                        }
                    });

                    view.removeOnAttachStateChangeListener(this);
                }

                @Override
                public void onViewDetachedFromWindow(View v) {
                    view.removeOnAttachStateChangeListener(this);
                }
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*put 5

代码片段。. .

public void hideKeyboard(Context activityContext){

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

    //android.R.id.content ( http://stackoverflow.com/a/12887919/2077479 )
    View rootView = ((Activity) activityContext)
            .findViewById(android.R.id.content).getRootView();

    imm.hideSoftInputFromWindow(rootView.getWindowToken(), 0);
}

public void showKeyboard(Context activityContext, final EditText editText){

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

    if (!editText.hasFocus()) {
        editText.requestFocus();
    }

    editText.post(new Runnable() {
        @Override
        public void run() {
            imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)


lxk*_*vlk 5

我将所有内容组合在一起,对我来说它有效:

public static void showKeyboardWithFocus(View v, Activity a) {
    try {
        v.requestFocus();
        InputMethodManager imm = (InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
        a.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

editText.post(new Runnable() {
    @Override
    public void run() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }
});
Run Code Online (Sandbox Code Playgroud)


Md *_*ury 5

Inside your manifest:

android:windowSoftInputMode="stateAlwaysVisible" - initially launched keyboard. android:windowSoftInputMode="stateAlwaysHidden" - initially hidden keyboard.

我也喜欢使用"adjustPan",因为当键盘启动时,屏幕会自动调整。

 <activity
      android:name="YourActivity"
      android:windowSoftInputMode="stateAlwaysHidden|adjustPan"/>
Run Code Online (Sandbox Code Playgroud)


bit*_*ale 5

对于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)
}
Run Code Online (Sandbox Code Playgroud)