关闭/隐藏Android软键盘

时间:2009-07-10 11:27:17

标签: android android-layout android-softkeyboard android-input-method soft-keyboard

我的布局中有EditTextButton

在编辑字段中写入并单击Button后,我想隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的一个例子?

123 个答案:

答案 0 :(得分:4304)

您可以使用InputMethodManager强制Android隐藏虚拟键盘,调用hideSoftInputFromWindow,传入包含焦点视图的窗口的标记。

// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

这将强制键盘在所有情况下都被隐藏。在某些情况下,您需要传递InputMethodManager.HIDE_IMPLICIT_ONLY作为第二个参数,以确保在用户未明确强制显示键盘时(仅通过按住菜单)隐藏键盘。

注意:如果您想在Kotlin中执行此操作,请使用: context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

Kotlin语法

// Check if no view has focus:
 val view = this.currentFocus
 view?.let { v ->
  val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager 
  imm?.let { it.hideSoftInputFromWindow(v.windowToken, 0) }
 }

答案 1 :(得分:1558)

为了帮助澄清这种疯狂,我想首先代表所有Android用户道歉,谷歌对软键盘的彻头彻尾的荒谬处理。对于同样简单的问题,有这么多答案的原因有很多,因为这个API与Android中的许多其他API一样,设计非常糟糕。我认为没有礼貌的方式陈述它。

我想要隐藏键盘。我期望为Android提供以下声明:Keyboard.hide()。结束。非常感谢你。但Android存在问题。您必须使用InputMethodManager隐藏键盘。好的,很好,这是Android的键盘API。但!您需要拥有Context才能访问IMM。现在我们遇到了问题。我可能想要从没有任何用途或需要任何Context的静态或实用程序类中隐藏键盘。或者更糟糕的是,IMM要求您指定要隐藏键盘FROM的View(或更糟糕的是,Window)。

这使得隐藏键盘变得如此具有挑战性。亲爱的谷歌:当我查找蛋糕的配方时,地球上没有RecipeProvider会拒绝向我提供配方,除非我先回答世界卫生组织,蛋糕将被和它吃掉。吃过!!

这个悲伤的故事以丑陋的事实结束:要隐藏Android键盘,您需要提供两种身份识别形式:Context以及ViewWindow

我已经创建了一个静态实用工具方法,只要你从Activity调用它就可以非常稳定地完成工作。

public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = activity.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

请注意,此实用程序方法仅在从Activity调用时才有效!上述方法调用目标getCurrentFocus的{​​{1}}来获取正确的窗口令牌。

但是假设您要隐藏Activity托管的EditText键盘?您无法使用上述方法:

DialogFragment

这不起作用,因为您将传递对hideKeyboard(getActivity()); //won't work 的主机Fragment的引用,在显示Activity时,该主机将无法集中控制!哇!所以,为了让键盘不受碎片的影响,我采用较低级别,更常见,更丑陋的方式:

Fragment

以下是从更多时间浪费在追逐此解决方案中收集到的一些其他信息:

关于windowSoftInputMode

还有另一个争论点需要注意。默认情况下,Android会自动将初始焦点分配给public static void hideKeyboardFrom(Context context, View view) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } 中的第一个EditText或可聚焦控件。由此可见,InputMethod(通常是软键盘)将通过显示自身来响应焦点事件。 Activity中的windowSoftInputMode属性设置为AndroidManifest.xml时,会指示键盘忽略此自动分配的初始焦点。

stateAlwaysHidden

几乎令人难以置信的是,当您触摸控件时,除了<activity android:name=".MyActivity" android:windowSoftInputMode="stateAlwaysHidden"/> 和/或focusable="false"分配给控件外,它似乎无法阻止键盘打开。显然,windowSoftInputMode设置仅适用于自动焦点事件,而不是关注触摸事件触发的事件。

因此,focusableInTouchMode="false"的名字确实非常糟糕。它也许应该被称为stateAlwaysHidden

希望这有帮助。


更新:获取窗口令牌的更多方法

如果没有焦点视图(例如,如果您刚刚更改了片段,则可能会发生),还有其他视图将提供有用的窗口令牌。

这些是上述代码ignoreInitialFocus的替代方法。这些代码并未明确提及您的活动。

在片段类中:

if (view == null)   view = new View(activity);

将片段view = getView().getRootView().getWindowToken(); 作为参数:

fragment

从您的内容正文开始:

view = fragment.getView().getRootView().getWindowToken();

更新2:如果您从后台打开应用,请清除焦点以避免再次显示键盘

将此行添加到方法的末尾:

view = findViewById(android.R.id.content).getRootView().getWindowToken();

答案 2 :(得分:772)

隐藏软键盘也很有用:

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

这可用于在用户实际触摸editText视图之前抑制软键盘。

答案 3 :(得分:325)

我还有一个隐藏键盘的解决方案:

InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

此处HIDE_IMPLICIT_ONLY位于showFlag0位置hiddenFlag。它会强行关闭软键盘。

答案 4 :(得分:141)

Meier的解决方案也适用于我。在我的情况下,我的应用程序的顶级是tabHost,我想在切换标签时隐藏关键字 - 我从tabHost视图中获取窗口标记。

tabHost.setOnTabChangedListener(new OnTabChangeListener() {
    public void onTabChanged(String tabId) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(tabHost.getApplicationWindowToken(), 0);
    }
}

答案 5 :(得分:130)

请在onCreate()

中尝试以下代码
EditText edtView=(EditText)findViewById(R.id.editTextConvertValue);
edtView.setInputType(0);

答案 6 :(得分:121)

<强>更新 我不知道为什么这个解决方案不再起作用(我刚刚在Android 23上测试过)。请改用Saurabh Pareek的解决方案。这是:

InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

旧答案:

//Show soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//hide keyboard :
 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

答案 7 :(得分:79)

protected void hideSoftKeyboard(EditText input) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(input.getWindowToken(), 0);    
}

答案 8 :(得分:65)

如果此处的所有其他答案对您不起作用,则还有另一种手动控制键盘的方法。

使用它创建一个函数来管理EditText的一些属性:

public void setEditTextFocus(boolean isFocused) {
    searchEditText.setCursorVisible(isFocused);
    searchEditText.setFocusable(isFocused);
    searchEditText.setFocusableInTouchMode(isFocused);

    if (isFocused) {
        searchEditText.requestFocus();
    }
}

然后,确保打开/关闭键盘EditText的onFocus:

searchEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (v == searchEditText) {
            if (hasFocus) {
                // Open keyboard
                ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(searchEditText, InputMethodManager.SHOW_FORCED);
            } else {
                // Close keyboard
                ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
            }
        }
    }
});

现在,每当你想手动打开键盘时,请致电:

setEditTextFocus(true);

关闭电话:

setEditTextFocus(false);

答案 9 :(得分:57)

到目前为止,

Saurabh Pareek有最好的答案。

不妨使用正确的标志。

/* hide keyboard */
((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
    .toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

/* show keyboard */
((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
    .toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);

实际使用示例

/* click button */
public void onClick(View view) {      
  /* hide keyboard */
  ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
      .toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

  /* start loader to check parameters ... */
}

/* loader finished */
public void onLoadFinished(Loader<Object> loader, Object data) {
    /* parameters not valid ... */

    /* show keyboard */
    ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
        .toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);

    /* parameters valid ... */
}

答案 10 :(得分:51)

从搜索到这里,我找到了一个适合我的答案

// Show soft-keyboard:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

// Hide soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

答案 11 :(得分:48)

简短回答

OnClick听众中使用onEditorAction

致电EditText的{​​{1}}
IME_ACTION_DONE

深入研究

我觉得这种方法更好,更简单,更符合Android的设计模式。 在上面的简单示例中(通常在大多数常见情况下),您将拥有一个具有焦点的button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { someEditText.onEditorAction(EditorInfo.IME_ACTION_DONE) } }); ,并且通常也是首先调用键盘的那个(它是绝对能够在许多常见场景中调用它)。以同样的方式,应该是释放键盘的那个,通常可以由EditText来完成。只需看看ImeAction EditText如何表现,您希望通过相同的方式实现相同的行为。


选中此related answer

答案 12 :(得分:43)

这应该有效:

public class KeyBoard {

    public static void show(Activity activity){
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
    }

    public static void hide(Activity activity){
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide
    }

    public static void toggle(Activity activity){
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm.isActive()){
            hide(activity); 
        } else {
            show(activity); 
        }
    }
}

KeyBoard.toggle(activity);

答案 13 :(得分:40)

我正在使用自定义键盘输入十六进制数字,因此我无法显示IMM键盘...

在v3.2.4_r1 setSoftInputShownOnFocus(boolean show)被添加以控制天气或不显示TextView获得焦点时的键盘,但它仍然隐藏,因此必须使用反射:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
    try {
        Method method = TextView.class.getMethod("setSoftInputShownOnFocus", boolean.class);
        method.invoke(mEditText, false);
    } catch (Exception e) {
        // Fallback to the second method
    }
}

对于旧版本,我使用OnGlobalLayoutListener获得了非常好的结果(但远非完美),在我的根视图中添加了ViewTreeObserver,然后检查键盘是否显示为这样:

@Override
public void onGlobalLayout() {
    Configuration config = getResources().getConfiguration();

    // Dont allow the default keyboard to show up
    if (config.keyboardHidden != Configuration.KEYBOARDHIDDEN_YES) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mRootView.getWindowToken(), 0);
    }
}

这最后一个解决方案可能会在短时间内显示键盘并使用选择手柄进行混乱。

当键盘进入全屏时,不会调用onGlobalLayout。为避免这种情况,请使用TextView#setImeOptions(int)或TextView XML声明:

android:imeOptions="actionNone|actionUnspecified|flagNoFullscreen|flagNoExtractUi"

更新:刚刚找到了哪些对话框用于永不显示键盘并适用于所有版本:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
        WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

答案 14 :(得分:30)

public void setKeyboardVisibility(boolean show) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if(show){
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }else{
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
    }
}

答案 15 :(得分:27)

我花了两天多的时间来完成线程中发布的所有解决方案,并发现它们缺乏这种或那种方式。我的确切要求是有一个100%可靠性的按钮显示或隐藏屏幕键盘。当键盘处于隐藏状态时,无论用户点击什么输入字段,都不应重新出现。当它处于可见状态时,无论用户点击什么按钮,键盘都不会消失。这需要在Android 2.2+上运行,直到最新的设备。

您可以在我的应用clean RPN中看到这方面的有效实施。

在许多不同的手机(包括froyo和姜饼设备)上测试了许多建议的答案后,很明显Android应用程序可以可靠地使用:

  1. 暂时隐藏键盘。它会在用户时重新出现 聚焦一个新的文本字段。
  2. 活动开始时显示键盘 并在活动上设置一个标志,表明他们的键盘应该 永远是可见的。此标志只能在活动时设置 初始化。
  3. 将活动标记为从不显示或允许使用 键盘。此标志只能在活动时设置 初始化。
  4. 对我来说,暂时隐藏键盘是不够的。在某些设备上,只要新文本字段被聚焦,它就会重新出现。由于我的应用程序在一个页面上使用多个文本字段,因此聚焦新文本字段将导致隐藏键盘再次弹回。

    不幸的是,列表中的第2项和第3项仅在启动活动时才具有可靠性。活动变得可见后,您无法永久隐藏或显示键盘。诀窍是当用户按下键盘切换按钮时实际重启您的活动。在我的应用程序中,当用户按下切换键盘按钮时,将运行以下代码:

    private void toggleKeyboard(){
    
        if(keypadPager.getVisibility() == View.VISIBLE){
            Intent i = new Intent(this, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            Bundle state = new Bundle();
            onSaveInstanceState(state);
            state.putBoolean(SHOW_KEYBOARD, true);
            i.putExtras(state);
    
            startActivity(i);
        }
        else{
            Intent i = new Intent(this, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            Bundle state = new Bundle();
            onSaveInstanceState(state);
            state.putBoolean(SHOW_KEYBOARD, false);
            i.putExtras(state);
    
            startActivity(i);
        }
    }
    

    这会导致当前活动将其状态保存到Bundle中,然后启动活动,通过布尔值来指示是否应显示或隐藏键盘。

    在onCreate方法中,运行以下代码:

    if(bundle.getBoolean(SHOW_KEYBOARD)){
        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(newEquationText,0);
        getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
    else{
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }
    

    如果应显示软键盘,则告诉InputMethodManager显示键盘,并指示窗口使软输入始终可见。如果应隐藏软键盘,则设置WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM。

    这种方法可以在我测试过的所有设备上可靠运行 - 从运行Android 2.2的4岁HTC手机到运行4.2.2的nexus 7。这种方法的唯一缺点是你需要小心处理后退按钮。由于我的应用程序基本上只有一个屏幕(它是一个计算器),我可以覆盖onBackPressed()并返回设备主屏幕。

答案 16 :(得分:25)

除了this all around solution之外,如果你想从任何地方关闭软键盘 而没有引用用于打开键盘的(EditText)字段,但仍然想要如果该字段是重点,你可以使用它(来自一个活动):

if (getCurrentFocus() != null) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}

答案 17 :(得分:22)

感谢this SO answer,我推导出以下内容,在我的情况下,滚动浏览ViewPager的片段时效果很好......

private void hideKeyboard() {   
    // Check if no view has focus:
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

private void showKeyboard() {   
    // Check if no view has focus:
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }
}

答案 18 :(得分:19)

以上答案适用于不同的情况但如果您想在视图中隐藏键盘并努力获得正确的上下文,请尝试以下操作:

setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        hideSoftKeyBoardOnTabClicked(v);
    }
}

private void hideSoftKeyBoardOnTabClicked(View v) {
    if (v != null && context != null) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

并获取上下文从构造函数中获取它:)

public View/RelativeLayout/so and so (Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.context = context;
    init();
}

答案 19 :(得分:18)

如果您想在单元或功能测试期间关闭软键盘,可以通过单击测试中的“后退按钮”来实现:

// Close the soft keyboard from a Test
getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);

我在引号中加上“后退按钮”,因为上面的内容不会触发相关活动的onBackPressed()。它只是关闭键盘。

确保暂停一会儿才能继续前进,因为关闭后退按钮需要一段时间,所以后续点击视图等,直到短暂停顿后才会注册(1秒后是足够长的时间)。

答案 20 :(得分:15)

以下是使用Mono for Android(AKA MonoDroid)进行操作的方法

InputMethodManager imm = GetSystemService (Context.InputMethodService) as InputMethodManager;
if (imm != null)
    imm.HideSoftInputFromWindow (searchbox.WindowToken , 0);

答案 21 :(得分:13)

这适用于我所有奇怪的键盘行为

private boolean isKeyboardVisible() {
    Rect r = new Rect();
    //r will be populated with the coordinates of your view that area still visible.
    mRootView.getWindowVisibleDisplayFrame(r);

    int heightDiff = mRootView.getRootView().getHeight() - (r.bottom - r.top);
    return heightDiff > 100; // if more than 100 pixels, its probably a keyboard...
}

protected void showKeyboard() {
    if (isKeyboardVisible())
        return;
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (getCurrentFocus() == null) {
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    } else {
        View view = getCurrentFocus();
        inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }
}

protected void hideKeyboard() {
    if (!isKeyboardVisible())
        return;
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View view = getCurrentFocus();
    if (view == null) {
        if (inputMethodManager.isAcceptingText())
            inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0);
    } else {
        if (view instanceof EditText)
            ((EditText) view).setText(((EditText) view).getText().toString()); // reset edit text bug on some keyboards bug
        inputMethodManager.hideSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

答案 22 :(得分:13)

在Manifest文件中添加到您的活动android:windowSoftInputMode="stateHidden"。例如:

<activity
            android:name=".ui.activity.MainActivity"
            android:label="@string/mainactivity"
            android:windowSoftInputMode="stateHidden"/>

答案 23 :(得分:11)

就我而言,我在操作栏中使用了SearchView。用户执行搜索后,键盘将再次弹出。

使用InputMethodManager没有关闭键盘。我不得不clearFocus并将搜索视图的焦点设置为false:

mSearchView.clearFocus();
mSearchView.setFocusable(false);

答案 24 :(得分:11)

使用此

this.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

答案 25 :(得分:11)

只需在您的活动中使用此优化代码:

if (this.getCurrentFocus() != null) {
    InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

答案 26 :(得分:11)

我几乎尝试了所有这些答案,我有一些随机问题,尤其是三星Galaxy s5。

我最终得到的是强迫节目和隐藏,它完美地运作:

/**
 * Force show softKeyboard.
 */
public static void forceShow(@NonNull Context context) {
    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

/**
 * Force hide softKeyboard.
 */
public static void forceHide(@NonNull Activity activity, @NonNull EditText editText) {
    if (activity.getCurrentFocus() == null || !(activity.getCurrentFocus() instanceof EditText)) {
        editText.requestFocus();
    }
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}

答案 27 :(得分:11)

在某些情况下,除其他所有方法外,此方法都可以使用。 这节省了我的一天:)

public static void hideSoftKeyboard(Activity activity) {
    if (activity != null) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (activity.getCurrentFocus() != null && inputManager != null) {
            inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
            inputManager.hideSoftInputFromInputMethod(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }
}

public static void hideSoftKeyboard(View view) {
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManager != null) {
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}

答案 28 :(得分:11)

简单易用的方法,只需调用 hideKeyboardFrom(YourActivity.this); 隐藏键盘

/**
 * This method is used to hide keyboard
 * @param activity
 */
public static void hideKeyboardFrom(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}

答案 29 :(得分:10)

public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}

在onTouchListener上调用之后:

findViewById(android.R.id.content).setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Utils.hideSoftKeyboard(activity);
        return false;
    }
});

答案 30 :(得分:10)

我遇到了这种情况,我的EditText也可以放在AlertDialog中,因此键盘应该在关闭时关闭。以下代码似乎可以在任何地方使用:

public static void hideKeyboard( Activity activity ) {
    InputMethodManager imm = (InputMethodManager)activity.getSystemService( Context.INPUT_METHOD_SERVICE );
    View f = activity.getCurrentFocus();
    if( null != f && null != f.getWindowToken() && EditText.class.isAssignableFrom( f.getClass() ) )
        imm.hideSoftInputFromWindow( f.getWindowToken(), 0 );
    else 
        activity.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN );
}

答案 31 :(得分:9)

有时你想要的只是输入按钮来折叠keyboard 给你EditText框提供属性

 android:imeOptions="actionDone" 

这会将Enter按钮更改为关闭键盘的Done按钮。

答案 32 :(得分:9)

对于打开键盘:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edtView, InputMethodManager.SHOW_IMPLICIT);

关闭/隐藏键盘:

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

答案 33 :(得分:9)

每次都像魔术一样工作

private void closeKeyboard() {
    InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

}

private void openKeyboard() {
    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }
}

答案 34 :(得分:9)

Kotlin Version通过Extension Function

使用kotlin扩展功能,显示和隐藏软键盘非常简单。

ExtensionFunctions.kt

import android.app.Activity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.fragment.app.Fragment

fun Activity.hideKeyboard(): Boolean {
    return (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
        .hideSoftInputFromWindow((currentFocus ?: View(this)).windowToken, 0)
}

fun Fragment.hideKeyboard(): Boolean {
    return (context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
        .hideSoftInputFromWindow((activity?.currentFocus ?: View(context)).windowToken, 0)
}

fun EditText.hideKeyboard(): Boolean {
    return (context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
        .hideSoftInputFromWindow(windowToken, 0)
}

fun EditText.showKeyboard(): Boolean {
    return (context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
        .showSoftInput(this, 0)
}

•使用情况

现在在您的ActivityFragment中,hideKeyboard()可以被访问,也可以从EditText的实例中调用它,例如:

editText.hideKeyboard()

答案 35 :(得分:8)

您还可以在EditText上使用setImeOption

我只是有一个非常类似的情况,我的布局包含EditText和搜索按钮。当我发现我可以在我的editText上将ime选项设置为“actionSearch”时,我意识到我甚至不再需要搜索按钮了。软键盘(在此模式下)有一个搜索图标,可用于启动搜索(键盘会按照您的预期自行关闭)。

答案 36 :(得分:7)

只需调用以下方法,它将在显示键盘时隐藏您的键盘。

public void hideKeyboard() {
    try {
        InputMethodManager inputmanager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputmanager != null) {
            inputmanager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
    } catch (Exception var2) {
    }

}

答案 37 :(得分:6)

对我有用..

EditText editText=(EditText)findViewById(R.id.edittext1);

将下面的代码放在onClick()

editText.setFocusable(false);
editText.setFocusableInTouchMode(true);

这里隐藏键盘,当我们点击按钮时,当我们触摸EditText键盘时将显示。

<强>(OR)

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

答案 38 :(得分:6)

有时您可以拥有一个活动,其中包含一个包含editText的行的列表视图,因此您必须在清单SOFT_INPUT_ADJUST_PAN中进行设置,然后键盘会显示出令人讨厌的内容。

如果您将其置于onCreate

的末尾,则以下workarround有效
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            }
        },100);

答案 39 :(得分:6)

试试这个

  • 很简单,您可以拨打Activity
 public static void hideKeyboardwithoutPopulate(Activity activity) {
    InputMethodManager inputMethodManager =
            (InputMethodManager) activity.getSystemService(
                    Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(
            activity.getCurrentFocus().getWindowToken(), 0);
}
  • MainActivitiy致电此
 hideKeyboardwithoutPopulate(MainActivity.this);

答案 40 :(得分:6)

如果有兴趣的话,我已经为Kotlin写了一个小小的扩展名,并没有对它进行过多次测试:

fun Fragment.hideKeyboard(context: Context = App.instance) {
    val windowToken = view?.rootView?.windowToken
    windowToken?.let {
        val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(windowToken, 0)
    }
}

App.instance是存储在Application

中的静态“this”应用程序对象

更新:在某些情况下,windowToken为null。我添加了使用反射来关闭键盘以检测键盘是否关闭的其他方法

/**
 * If no window token is found, keyboard is checked using reflection to know if keyboard visibility toggle is needed
 *
 * @param useReflection - whether to use reflection in case of no window token or not
 */
fun Fragment.hideKeyboard(context: Context = MainApp.instance, useReflection: Boolean = true) {
    val windowToken = view?.rootView?.windowToken
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    windowToken?.let {
        imm.hideSoftInputFromWindow(windowToken, 0)
    } ?: run {
        if (useReflection) {
            try {
                if (getKeyboardHeight(imm) > 0) {
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
                }
            } catch (exception: Exception) {
                Timber.e(exception)
            }
        }
    }
}

fun getKeyboardHeight(imm: InputMethodManager): Int = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight").invoke(imm) as Int

答案 41 :(得分:5)

public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager)activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}

答案 42 :(得分:5)

AndroidManifest.xml下的<activity..> android:windowSoftInputMode="stateAlwaysHidden"

答案 43 :(得分:5)

如果您想使用Java代码隐藏键盘,请使用:

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

或者,如果您想要始终隐藏键盘,请在AndroidManifest中使用它:

 <activity
 android:name=".activities.MyActivity"
 android:configChanges="keyboardHidden"  />

答案 44 :(得分:5)

这是工作..

只需在函数

中传递当前活动实例
 public void isKeyBoardShow(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    if (imm.isActive()) {
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide
    } else {
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
    }
}

答案 45 :(得分:5)

现在,将近 12 年后,我们终于有了一种官方的、向后兼容的方法来使用 AndroidX Core 1.5+ 来做到这一点:

fun View.hideKeyboard() = ViewCompat.getWindowInsetsController(this)
    ?.hide(WindowInsetsCompat.Type.ime())

或专门用于片段:

fun Fragment.hideKeyboard() = ViewCompat.getWindowInsetsController(requireView())
    ?.hide(WindowInsetsCompat.Type.ime())

答案 46 :(得分:4)

简单的代码: 在 onCreate()

中使用此代码
getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);

答案 47 :(得分:4)

实际上,Android权限始终在提供新的更新,但它们并未解决所有Android开发人员在开发中面临的旧缺陷,默认情况下应由Android权限来处理,从EditText更改焦点时应隐藏/显示软输入键盘选项。但是对此感到抱歉,他们没有进行管理。好吧,离开它。

下面是在“活动”或“片段”中显示/隐藏/切换键盘选项的解决方案。

显示视图的键盘:

/**
 * open soft keyboard.
 *
 * @param context
 * @param view
 */
public static void showKeyBoard(Context context, View view) {
    try {
        InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        keyboard.showSoftInput(view, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

显示带有“活动”上下文的键盘:

/**
 * open soft keyboard.
 *
 * @param mActivity context
 */
public static void showKeyBoard(Activity mActivity) {
    try {
        View view = mActivity.getCurrentFocus();
        if (view != null) {
            InputMethodManager keyboard = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            keyboard.showSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.SHOW_FORCED);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

显示具有片段上下文的键盘:

/**
 * open soft keyboard.
 *
 * @param mFragment context
 */
public static void showKeyBoard(Fragment mFragment) {
    try {
        if (mFragment == null || mFragment.getActivity() == null) {
            return;
        }
        View view = mFragment.getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager keyboard = (InputMethodManager) mFragment.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            keyboard.showSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.SHOW_FORCED);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

隐藏视图的键盘:

/**
 * close soft keyboard.
 *
 * @param context
 * @param view
 */
public static void hideKeyBoard(Context context, View view) {
    try {
        InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        keyboard.hideSoftInputFromWindow(view.getWindowToken(), 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

隐藏带有活动上下文的键盘:

/**
 * close opened soft keyboard.
 *
 * @param mActivity context
 */
public static void hideSoftKeyboard(Activity mActivity) {
    try {
        View view = mActivity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

隐藏具有片段上下文的键盘:

/**
 * close opened soft keyboard.
 *
 * @param mFragment context
 */
public static void hideSoftKeyboard(Fragment mFragment) {
    try {
        if (mFragment == null || mFragment.getActivity() == null) {
            return;
        }
        View view = mFragment.getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) mFragment.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

切换键盘:

/**
 * toggle soft keyboard.
 *
 * @param context
 */
public static void toggleSoftKeyboard(Context context) {
    try {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

答案 48 :(得分:4)

这里都是hide&show方法。

科特林

fun hideKeyboard(activity: Activity) {
    val v = activity.currentFocus
    val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(v != null)
    imm.hideSoftInputFromWindow(v!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

private fun showKeyboard(activity: Activity) {
    val v = activity.currentFocus
    val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(v != null)
    imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT)
}

Java

public static void hideKeyboard(Activity activity) {
    View v = activity.getCurrentFocus();
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert imm != null && v != null;
    imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

private static void showKeyboard(Activity activity) {
    View v = activity.getCurrentFocus();
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert imm != null && v != null;
    imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
}

答案 49 :(得分:4)

如果您使用Kotlin开发应用程序,那真的很容易。

添加此扩展功能:

活动:

fun Activity.hideKeyboard() {
    val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    val view = currentFocus
    if (view != null) {
        inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }
}

对于片段:

fun Fragment.hideKeyboard() {
    activity?.let {
        val inputManager = it.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val view = it.currentFocus
        if (view != null) {
            inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }
}

现在,您可以在片段或活动中简单调用:

 hideKeyboard()

答案 50 :(得分:4)

使用AndroidX,我们将获得一种显示/隐藏键盘的惊人方法。阅读Release Notes - 1.5.0-alpha02。现在如何隐藏/显示键盘

const Schema = mongoose.Schema;

    const sodaSchema = new Schema(
      {
        name: {
          type: String,
          required: true,
        },
        drinker: {
          type: Schema.Types.ObjectId,
          ref: "Drinkers",
        },
      },
      { timestamps: true }
    );

链接我自己的答案How to check visibility of software keyboard in Android?和一个Amazing blog which includes more of this change (even more than it)

答案 51 :(得分:3)

public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager) activity
            .getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
            .getWindowToken(), 0);
}

答案 52 :(得分:3)

试试这个

public void disableSoftKeyboard(final EditText v) {
    if (Build.VERSION.SDK_INT >= 11) {
        v.setRawInputType(InputType.TYPE_CLASS_TEXT);
        v.setTextIsSelectable(true);
    } else {
        v.setRawInputType(InputType.TYPE_NULL);
        v.setFocusable(true);
    }
}

答案 53 :(得分:3)

简单的方法家伙: 试试这个...

private void closeKeyboard(boolean b) {

        View view = this.getCurrentFocus();

        if(b) {
            if (view != null) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
        else {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, 0);
        }
    }

答案 54 :(得分:3)

final RelativeLayout llLogin = (RelativeLayout) findViewById(R.id.rl_main);
        llLogin.setOnTouchListener(
                new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent ev) {
                        InputMethodManager imm = (InputMethodManager) this.getSystemService(
                                Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
                        return false;
                    }
                });

答案 55 :(得分:3)

以下是最佳解决方案

解决方案1)将inputType设置为“text”

  [HttpPost]
        public bool AddImages(ImageModel Image)
        {
            if (!ModelState.IsValid)
            {
                return false;
            }
            return true;
        }

这也可以通过编程方式完成。方法setInputType()(继承自TextView)。

<EditText
android:id="@+id/my_edit_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Tap here to type"
android:inputType="text" />

解决方案2)使用InputMethodManager.hideSoftInputFromWindow()

EditText editText = (EditText) findViewById(R.id.my_edit_text);
editText.setRawInputType(InputType.TYPE_CLASS_TEXT | 
InputType.TYPE_TEXT_VARIATION_NORMAL);

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

答案 56 :(得分:3)

非常简单

我在所有项目中都这样做,并且像梦一样工作。在您的声明layout.xml中,只需添加以下一行:

android:focusableInTouchMode="true"

完整代码示例:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusableInTouchMode="true">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ListView>

</android.support.constraint.ConstraintLayout>

答案 57 :(得分:3)

要在按钮操作上手动隐藏键盘,请单击:

/**
 * Hides the already popped up keyboard from the screen.
 *
 */
public void hideKeyboard() {
    try {
        // use application level context to avoid unnecessary leaks.
        InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        assert inputManager != null;
        inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

要将键盘隐藏在屏幕上除edittext以外的任何位置 在您的活动中覆盖此方法:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View view = getCurrentFocus();
    if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        view.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + view.getLeft() - scrcoords[0];
        float y = ev.getRawY() + view.getTop() - scrcoords[1];
        if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
            ((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
    }
    return super.dispatchTouchEvent(ev);
}

答案 58 :(得分:3)

调用此方法可以隐藏软键盘

array([[    1,     0,     4,     3],
       [   20,   300,  1000, 20000]])

答案 59 :(得分:3)

下面的代码将帮助您创建可从任何地方调用的泛型函数。

import android.app.Activity
import android.content.Context
import android.support.design.widget.Snackbar
import android.view.View
import android.view.inputmethod.InputMethodManager

public class KeyboardHider {
    companion object {

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

    }

}

使用一行代码从任何地方调用上述方法。

CustomSnackbar.hideKeyboard(view, this@ActivityName)

视图可以是任何东西,例如活动的根布局。

答案 60 :(得分:3)

通过将Generic方法添加到Utility或Helper类。只需自称即可隐藏和显示键盘

fun AppCompatActivity.hideKeyboard() {
            val view = this.currentFocus
            if (view != null) {
                val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(view.windowToken, 0)
            }
           window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)

        }


 fun AppCompatActivity.showKeyboard() {
            val view = this.currentFocus
            if (view != null) {
                val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(view.windowToken, 0)
            }                     window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)

        }

答案 61 :(得分:3)

从片段移动到片段时

fun hideKeyboard(activity: Activity?): Boolean {
    val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
    if (inputManager != null) {
        val currentFocus = activity?.currentFocus
        if (currentFocus != null) {
            val windowToken = currentFocus.windowToken
            if (windowToken != null) {
                return inputManager.hideSoftInputFromWindow(windowToken, 0)
            }
        }
    }
    return false
}

fun showKeyboard(editText: EditText) {
    val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(editText.windowToken, 0)
    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0)
    editText.requestFocus()
}

答案 62 :(得分:2)

我部分地从xml创建了一个布局,部分是从自定义布局引擎创建的,这个布局引擎都是在代码中处理的。唯一对我有用的是跟踪键盘是否打开,并按如下方式使用键盘切换方法:

public class MyActivity extends Activity
{
    /** This maintains true if the keyboard is open. Otherwise, it is false. */
    private boolean isKeyboardOpen = false;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater;
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(context.getResources().getIdentifier("main", "layout", getPackageName()), null);

        setContentView(contentView);
        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() 
        {
            public void onGlobalLayout() 
            {
                Rect r = new Rect();
                contentView.getWindowVisibleDisplayFrame(r);
                int heightDiff = contentView.getRootView().getHeight() - (r.bottom - r.top);
                if (heightDiff > 100) 
                    isKeyboardVisible = true;
                else
                    isKeyboardVisible = false;
             });
         }
    }

    public void closeKeyboardIfOpen()
    {
        InputMethodManager imm;
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (isKeyboardVisible)
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    }   
}

答案 63 :(得分:2)

此方法始终不惜任何代价。只需在任何想要隐藏键盘的地方使用它

public static void hideSoftKeyboard(Context mContext,EditText username){
        if(((Activity) mContext).getCurrentFocus()!=null && ((Activity) mContext).getCurrentFocus() instanceof EditText){
            InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(username.getWindowToken(), 0);
        }
    }

像这样使用:

无论Android的版本是什么。这种方法肯定会起作用

答案 64 :(得分:2)

这对我有用。

public static void hideKeyboard(Activity act, EditText et){
    Context c = act.getBaseContext();
    View v = et.findFocus();
    if(v == null)
        return;
    InputMethodManager inputManager = (InputMethodManager) c.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

答案 65 :(得分:2)

您只需将此代码添加到要隐藏软键盘的位置“

即可
                        // Check if no view has focus:
                            View view = getCurrentFocus();
                            if (view != null) {
                                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                            }

答案 66 :(得分:2)

在Android中,通过InputMethodManage隐藏Vkeyboard,您可以通过传入包含焦点视图的窗口的标记来隐藏软件输入.FromWindow。

View view = this.getCurrentFocus();
if (view != null) {  
InputMethodManager im = 
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

通过调用editText.clearFocus()然后InputMethodManager.HIDE_IMPLICIT_ONLY甚至可以正常工作

答案 67 :(得分:2)

在科特林

fun hideKeyboard(activity: BaseActivity) {
        val view = activity.currentFocus?: View(activity)
        val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

答案 68 :(得分:2)

project Default is

   for Source_Dirs use ("src");
   for Object_Dir use "obj";
   for Main use ("main.adb");

   package Compiler is
      for Local_Configuration_Pragmas use "gnat.adc";
   end Compiler;

end Default;

它将起作用。...@询问

答案 69 :(得分:2)

如果您需要在片段中隐藏键盘,则此方法有效。

public static void hideSoftKeyboard(Context context, View view) {
    if (context != null && view != null) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

对于视图,只需传入

getView() method

答案 70 :(得分:2)

感谢上帝,它得到了官方支持,after 11 years

首先将依赖项 implementation 'androidx.core:core-ktx:1.6.0-beta01' 添加到 app gradle

fun View.showKbd() {
    (this.context as? Activity)?.let {
        it.showKbd()
    }
}
fun View.hideKbd() {
    (this.context as? Activity)?.let {
        it.hideKbd()
    }
}

fun Fragment.showKbd() {
    activity?.let {
        it.showKbd()
    }
}
fun Fragment.hideKbd() {
    activity?.let {
        it.hideKbd()
    }
}

fun Context.showKbd() {
    (this as? Activity)?.let {
        it.showKbd()
    }
}
fun Context.hideKbd() {
    (this as? Activity)?.let {
        it.hideKbd()
    }
}

fun Activity.showKbd(){
    WindowInsetsControllerCompat(window, window.decorView).show(WindowInsetsCompat.Type.ime())
}
fun Activity.hideKbd(){
    WindowInsetsControllerCompat(window, window.decorView).hide(WindowInsetsCompat.Type.ime())
}

答案 71 :(得分:1)

在绝望中尝试所有方法,结合所有方法,当然键盘不会在Android 4.0.3中关闭(它在Honeicomb AFAIR中有效)。

突然间,我发现了一个显然是胜利的组合:

textField.setRawInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_TEXT_VARIATION_NORMAL);

结合您常用的食谱

blahblaj.hideSoftInputFromWindow ...

希望这可以阻止某人自杀......我很接近它。当然,我不知道它为什么会起作用。

答案 72 :(得分:1)

public static void closeInput(final View caller) {  
    caller.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) caller.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(caller.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }, 100);
}

此方法通常有效,但有一个条件:您不能设置android:windowSoftInputMode="any_of_these"

答案 73 :(得分:1)

使用SearchView的替代方法是使用此代码:

searchView = (SearchView) searchItem.getActionView();    
searchView.setOnQueryTextListener(new OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        InputMethodManager imm = (InputMethodManager)
        getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(searchView.getApplicationWindowToken(), 0);
    }
}

这是ActionBar中的SearchView搜索框,当提交查询文本时(用户按下Enter键或搜索按钮/图标),InputMethodManager代码被激活并使你的软键盘下降。此代码已放入我的onCreateOptionsMenu()searchItem来自MenuItem,它是onCreateOptionsmenu()默认代码的一部分。感谢@mckoss提供了大量此代码!

答案 74 :(得分:1)

尽管有这些答案,但为了简单起见,我已经写了一个常用的方法来做到这一点:

/**
 * hide soft keyboard in a activity
 * @param activity
 */
public static void hideKeyboard (Activity activity){
    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    if (activity.getCurrentFocus() != null) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
    }
}

答案 75 :(得分:1)

您可以为任何视图创建扩展功能

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

与“活动”结合使用的示例

window.decorView.hideKeyboard();

与View结合使用的示例

etUsername.hideKeyboard();

快乐编码...

答案 76 :(得分:1)

对于Xamarin.Android:

public void HideKeyboard()
{
    var imm = activity.GetSystemService(Context.InputMethodService).JavaCast<InputMethodManager>();
    var view = activity.CurrentFocus ?? new View(activity);
    imm.HideSoftInputFromWindow(view.WindowToken, HideSoftInputFlags.None);
}

答案 77 :(得分:1)

 fun hideKeyboard(appCompatActivity: AppCompatActivity) {
        val view = appCompatActivity.currentFocus
        val imm = appCompatActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

答案 78 :(得分:1)

public void hideKeyboard() 
{
    if(getCurrentFocus()!=null) 
    {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}


public void showKeyboard(View mView) {
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    mView.requestFocus();
    inputMethodManager.showSoftInput(mView, 0);
}

答案 79 :(得分:1)

在Kotlin中的Wiki答案:

1-在文件(例如,包含所有顶级功能的文件)中创建top-level function

fun Activity.hideKeyboard(){
    val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    var view = currentFocus
    if (view == null) { view = View(this) }
    imm.hideSoftInputFromWindow(view.windowToken, 0)
}

2-然后在您需要的任何活动中调用它:

this.hideKeyboard()

答案 80 :(得分:1)

对于Kotlin用户,这里有一种适用于我的用例的kotlin扩展方法:

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

将其放入一个名为ViewExtensions(或您拥有的文件)的文件中,然后像普通方法一样在您的视图上调用它。

答案 81 :(得分:1)

嗨,这很简单,如果您正在使用Kotlin,我相信您也可以轻松地将代码转换为Java,例如,在您的活动加载时使用此函数,例如在onCreate()中调用它。

fun hideKeybord (){
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (inputManager.isAcceptingText){
    inputManager.hideSoftInputFromWindow(currentFocus.windowToken, 0)
}

}

正如我提到的,请在您的onCreate()方法中调用此函数,然后将此android:windowSoftInputMode="stateAlwaysHidden"行添加到manafest.xml文件中的活动中,如下所示:

<activity
    android:name=".Activity.MainActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar"
    android:windowSoftInputMode="stateAlwaysHidden">

答案 82 :(得分:1)

在BaseActivity和BaseFragment中使整个应用程序成为通用方法

onCreate()中初始化inputMethodManager

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

使此方法隐藏和显示键盘

public void hideKeyBoard(View view) {
     if (view != null) {
         inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
      }
 }

public void showKeyboard(View view, boolean isForceToShow) {
      if (isForceToShow)
         inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
      else if (view != null)
           inputMethodManager.showSoftInput(view, 0);
}

答案 83 :(得分:1)

在Kotli中,我使用Kotlin扩展名来显示和隐藏键盘。

fun View.showKeyboard() {
  this.requestFocus()
  val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
  inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

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

答案 84 :(得分:1)

在Android 10(API 29)中片段化工作

val activityView = activity?.window?.decorView?.rootView
activityView?.let {
    val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    imm?.hideSoftInputFromWindow(it.windowToken, 0)
}

答案 85 :(得分:1)

科特林

class KeyboardUtils{
    
    companion object{
        fun hideKeyboard(activity: Activity) {
            val imm: InputMethodManager = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            var view: View? = activity.currentFocus
            if (view == null) {
                view = View(activity)
            }
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }
}

然后在任何需要的地方调用它

片段

KeyboardUtils.hideKeyboard(requireActivity())

活动

 KeyboardUtils.hideKeyboard(this)

答案 86 :(得分:1)

片段中的科特林解决方案:

 <div class="myresult"></div>
 <div class = "buscar">
 <button id="display" class="mybutton">Revisar</button>
 </div>

检查清单是否没有与您的活动相关的参数:

fun hideSoftKeyboard() {
        val view = activity?.currentFocus
        view?.let { v ->
            val imm =
                activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager // or context
            imm.hideSoftInputFromWindow(v.windowToken, 0)
        }
}

答案 87 :(得分:1)

有很多答案,如果毕竟什么都不起作用,这是一个提示:), 你可以制作一个 EditText 和,

edittext.setAlpha(0f);

由于alpha方法,这个edittext不会被看到, 现在使用上面的答案,了解如何使用 EditText 显示/隐藏软键盘。

答案 88 :(得分:1)

在 Kotlin 中只需使用这两种方法来显示和隐藏键盘。

fun showKeyboard() =
    (context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as? InputMethodManager)!!
        .toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)

fun hideKeyboard() =
    (context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as? InputMethodManager)!!
        .hideSoftInputFromWindow(editText.windowToken, 0)

这里 editText 是您当前的视图,

答案 89 :(得分:1)

这是使用 Kotlin 隐藏软键盘的最简单方法:

//hides soft keyboard anything else is tapped( screen, menu bar, buttons, etc. )
override fun dispatchTouchEvent( ev: MotionEvent? ): Boolean {
    if ( currentFocus != null ) {
        val imm = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
        imm.hideSoftInputFromWindow( currentFocus!!.windowToken, 0 )
    }
    return super.dispatchTouchEvent( ev )
}

答案 90 :(得分:1)

<div *ngFor="let group of formArr$ | async; let i = index">
  <div formArrayName="formArr">
    <div [formGroupName]="i">
      <input formControlName="formCtrl">
    </div>
  </div>
</div>

答案 91 :(得分:1)

    hide soft keyboard in Kotlin using globally using method. For using globally in Kotlin you need to create Singletone class. In Kotlin we are using object keyword for creating Singletone class.
    
    
    object Extensions {
    
      fun View.hideKeyboard() {
            val inputMethodManager =                                                 
            context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE)           
            as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
        }
    }

In your activity of fragment class where you need to hide the keyboard you can call this function with mainlayout id like below

//constraintEditLayout is my main view layout, if you are using other layout like relative or linear layouts you can call with that layout id
constraintEditLayout.hideKeyboard()

答案 92 :(得分:0)

private void hideSoftKeyboard() {
    View view = getView();
    if (view != null) {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
                .getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

答案 93 :(得分:0)

/** 
 *
 *   Hide I Said!!!
 *
 */
public static boolean hideSoftKeyboard(@NonNull Activity activity) {
    View currentFocus = activity.getCurrentFocus();
    if (currentFocus == null) {
        currentFocus = activity.getWindow().getDecorView();
        if (currentFocus != null) {
            return getSoftInput(activity).hideSoftInputFromWindow(currentFocus.getWindowToken(), 0, null);
        }
    }
    return false;
}

public static boolean hideSoftKeyboard(@NonNull Context context) {
   if(Activity.class.isAssignableFrom(context.getClass())){
       return hideSoftKeyboard((Activity)context);
   }
   return false;
}

public static InputMethodManager getSoftInput(@NonNull Context context) {
    return (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
}

答案 94 :(得分:0)

用try catch包围它,所以键盘已经关闭,应用程序不会崩溃:

try{

View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}catch (Exception e)
{
  e.printStackTrace();
}

答案 95 :(得分:0)

use Text watcher instead of EditText.and after you finished entering the input 

你可以使用

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

答案 96 :(得分:0)

您只需在清单活动代码

中写一行
 android:windowSoftInputMode="stateAlwaysHidden|adjustPan"

它会起作用。

答案 97 :(得分:0)

在阅读了上述所有答案后,在另一篇文章中,我仍然没有成功地让键盘自动打开。

在我的项目中,我动态地创建了一个对话框(AlertDialog)(通过无需编程或用最少的XML编程)。

所以我做了类似的事情:

    dialogBuilder = new AlertDialog.Builder(activity);

    if(dialogBuilder==null)
        return false; //error

    inflater      = activity.getLayoutInflater();
    dialogView    = inflater.inflate(layout, null);
    ...

在完成设置所有视图(TextView,ImageView,EditText等)后,我做了:

        alertDialog = dialogBuilder.create();

        alertDialog.show();

在解决了所有答案之后,我发现大多数答案都是 IF 你知道 WHERE 提出要求......这是所有人的关键。

所以,诀窍是把它设置为 BEFORE :在我的情况下创建对话:alertDialog.show(),这就像魅力一样:

        alertDialog = dialogBuilder.create();           
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        //And only when everything is finished - let's bring up the window - 
        alertDialog.show();

        //Viola... keyboard is waiting for you open and ready...
        //Just don't forget to request focus for the needed view (i.e. EditText..)

我非常确定这个原则与所有窗口相同,所以要注意你的&#34; showKeyboard&#34;代码 - 它应该在窗口启动之前。

来自Android SDK开发团队的一个小请求:

我认为这一切都是不必要的,因为你可以看到来自世界各地的成千上万的程序员正在处理这个荒谬而琐碎的问题,而它的解决方案应该简洁明了: 恕我直言,如果我得到requestFocus()面向输入的视图(如EditText),键盘应自动打开,除非用户要求不 - ,所以,我认为requestFocus()方法是键在这里,应该接受默认值为true的布尔showSoftKeyboard:View.requestFocus(boolean showSoftKeyboard);

希望这能帮助像我这样的人。

答案 98 :(得分:0)

Kotlin版

val imm: InputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

答案 99 :(得分:0)

如果您的应用程序定位 API级别21或更高级别,则使用默认方法:

editTextObj.setShowSoftInputOnFocus(false);

确保在EditText XML标记中设置了以下代码。

<EditText  
    ....
    android:enabled="true"
    android:focusable="true" />

答案 100 :(得分:0)

一些kotlin代码:

隐藏活动中的键盘:

(currentFocus ?: View(this))
            .apply { (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
                        .hideSoftInputFromWindow(windowToken, 0) }

答案 101 :(得分:0)

我正在使用以下Kotlin活动扩展名:

/**
 * Hides soft keyboard if is open.
 */
fun Activity.hideKeyboard() {
    currentFocus?.windowToken?.let {
        (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager?)
                ?.hideSoftInputFromWindow(it, InputMethodManager.HIDE_NOT_ALWAYS)
    }
}

/**
 * Shows soft keyboard and request focus to given view.
 */
fun Activity.showKeyboard(view: View) {
    view.requestFocus()
    currentFocus?.windowToken?.let {
        (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager?)
                ?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
    }
}

答案 102 :(得分:0)

要在应用程序启动时显示键盘:

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        view.requestFocus();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            }
        }, 1000);

答案 103 :(得分:0)

在Kotlin尝试

 private fun hideKeyboard(){
    val imm = activity!!.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(activity!!.currentFocus!!.windowToken, 0)
}

尝试使用Java

 private void hideKeyboard(){
  InputMethodManager imm =(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}

答案 104 :(得分:0)

此代码段可以帮助您:

    final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null && inputMethodManager.isActive()) {
        if (getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

可以根据需要用不同的方法调用它(例如onPause,onResume,onRestart ...)

答案 105 :(得分:0)

首先,您应该从XML文件中添加 android:imeOptions 字段,并将其值更改为 actionUnspecified | actionGo ,如下所示

 <android.support.design.widget.TextInputEditText
                    android:id="@+id/edit_text_id"
                    android:layout_width="fill_parent"
                    android:layout_height="@dimen/edit_text_height"
                    android:imeOptions="actionUnspecified|actionGo"
                    />

然后在java类中添加 setOnEditorActionListener 并按如下所示添加InputMethodManager

enterOrderNumber.setOnEditorActionListener(new TextView.OnEditorActionListener(){

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_GO) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
            return true;
        }
        return false;
    }
});

答案 106 :(得分:0)

这对我来说很有效。它位于Kotlin中,用于隐藏键盘。

private fun hideKeyboard() {
        val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val focusedView = activity?.currentFocus
        if (focusedView != null) {
            inputManager.hideSoftInputFromWindow(focusedView.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

答案 107 :(得分:0)

只需在特定活动中的AndroidManifest中添加以下行即可。

<activity
        android:name=".MainActivity"
        android:screenOrientation="portrait">
        android:windowSoftInputMode="adjustPan"/>

答案 108 :(得分:0)

在您的Button editText.setEnabled(false);editText.setEnabled(true);方法中仅onClick()个简单的解决方法。

答案 109 :(得分:0)

尝试一下 强制完全使用Android软输入键盘

  

在Helper类中创建方法。

db.ApplicationLog.find({
"CreatedTimestamp": {
    $gte: 
        new Date(new Date().setDate(new Date().getDate()-1))
}

答案 110 :(得分:0)

一种简便的方法是在EditText视图中设置以下属性。

android:imeOptions="actionDone" 

答案 111 :(得分:0)

针对Kotlin爱好者。我创建了两个扩展功能。为了使hideKeyboard有趣,您可以将edittext的实例作为视图传递。

fun Context.hideKeyboard(view: View) {
    (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.apply {
        hideSoftInputFromWindow(view.windowToken, 0)
    }
}

fun Context.showKeyboard() {
    (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.apply {
        toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
    }
}

答案 112 :(得分:0)

只需在您的EditTect视图中添加此属性即可隐藏键盘。

android:focusable="false"

答案 113 :(得分:0)

您也可以使用此代码段在Kotlin中隐藏键盘。

 fun hideKeyboard(activity: Activity?) {
    val inputManager: InputMethodManager? = 
    activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? 
    InputMethodManager
    // check if no view has focus:
    val v = activity?.currentFocus ?: return
    inputManager?.hideSoftInputFromWindow(v.windowToken, 0)
 }

答案 114 :(得分:0)

Android 11中有一个名为WindowInsetsController的新API,Apps可以从任何视图访问控制器,通过它们我们可以使用hide()show()方法

val controller = view.windowInsetsController

// Show the keyboard (IME)
controller.show(Type.ime())

// Hide the keyboard
controller.hide(Type.ime())

请参阅https://developer.android.com/reference/android/view/WindowInsetsController

答案 115 :(得分:0)

 //In Activity
        View v = this.getCurrentFocus();
        if (v != null) {
            InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }


//In Fragment
        View v = getActivity().getCurrentFocus();
        if (v != null) {
            InputMethodManager im = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
```

答案 116 :(得分:0)

这对我有用,您只需要在其中传递元素即可。

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

答案 117 :(得分:0)

如果您将自己的.xml设置为android:focused =“ true”,那么他将无法工作,因为它是一个不可更改的集合。

所以解决方案: android:focusedByDefault =“ true”

比他将要设置一次并且可以隐藏/显示键盘

答案 118 :(得分:0)

不要忘记:在智能手机的系统设置中,“输入法和语言 -> 物理键盘 -> 显示屏幕键盘 -> 开/关”。此设置会“干扰”此处的所有编程解决方案!我也必须禁用/启用此设置才能完全隐藏/显示屏幕键盘!因为我正在为设备 MC2200 进行开发,所以我使用“EMDK 配置文件管理 -> Ui 管理器 -> 虚拟键盘状态 -> 显示/隐藏”

答案 119 :(得分:0)

这对我有用

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm.isActive())
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

答案 120 :(得分:0)

当您触摸编辑文本外部或其他任何地方时,此代码将帮助您隐藏键盘。您需要将此代码添加到您的活动中,或者您可以在项目的父活动中编写,它也会在 webview 中隐藏您的键盘。

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View v = getCurrentFocus();

    if (v != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && v instanceof EditText &&
            !v.getClass().getName().startsWith("android.webkit.")) {
        int[] sourceCoordinates = new int[2];
        v.getLocationOnScreen(sourceCoordinates);
        float x = ev.getRawX() + v.getLeft() - sourceCoordinates[0];
        float y = ev.getRawY() + v.getTop() - sourceCoordinates[1];

        if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()) {
            hideKeyboard(this);
        }

    }
    return super.dispatchTouchEvent(ev);
}

private void hideKeyboard(Activity activity) {
    if (activity != null && activity.getWindow() != null) {
        activity.getWindow().getDecorView();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
        }
    }
}

public static void hideKeyboard(View view) {
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null)
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

答案 121 :(得分:-1)

我已经尝试了所有解决方案,但没有解决方案适合我,所以我找到了我的解决方案: 你应该有布尔变量,如:

public static isKeyboardShowing = false;
InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
            .getSystemService(Context.INPUT_METHOD_SERVICE);

在触摸屏事件中,您致电:

@Override
public boolean onTouchEvent(MotionEvent event) {
    if(keyboardShowing==true){
        inputMethodManager.toggleSoftInput(InputMethodManager.RESULT_UNCHANGED_HIDDEN, 0);
        keyboardShowing = false;
    }
    return super.onTouchEvent(event);
}

在EditText中随处可见:

yourEditText.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            yourClass.keyboardShowing = true;

        }
    });

答案 122 :(得分:-3)

这对我有用:

 @Override
 public boolean dispatchTouchEvent(MotionEvent event) {
View v = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);

if (v instanceof EditText) {
    View w = getCurrentFocus();
    int scrcoords[] = new int[2];
    w.getLocationOnScreen(scrcoords);
    float x = event.getRawX() + w.getLeft() - scrcoords[0];
    float y = event.getRawY() + w.getTop() - scrcoords[1];

    Log.d("Activity",
            "Touch event " + event.getRawX() + "," + event.getRawY()
                    + " " + x + "," + y + " rect " + w.getLeft() + ","
                    + w.getTop() + "," + w.getRight() + ","
                    + w.getBottom() + " coords " + scrcoords[0] + ","
                    + scrcoords[1]);
    if (event.getAction() == MotionEvent.ACTION_UP
            && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w
                    .getBottom())) {

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getCurrentFocus()
                .getWindowToken(), 0);
    }
}
return ret;
}
相关问题