如何以编程方式关闭/隐藏 Android 软键盘?

How can I close/hide the Android soft keyboard programmatically?

提问人: 提问时间:7/10/2009 最后编辑:30 revs, 18 users 21%Vidar Vestnes 更新时间:10/18/2023 访问量:1822686

问:

我的布局中有一个和一个。EditTextButton

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

android android-edittext android-softkeyboard android-input-method soft-keyboard

评论

19赞 AlikElzin-kilaka 6/1/2011
如果您只有一个 EditText 和几个按钮(如复选框和单选按钮)怎么办?唯一需要键盘的地方是单个 EditText。您如何注册以知道选择/单击了其他内容以隐藏键盘?
18赞 rupps 5/15/2013
我觉得自己很傻。我无法在 ICS 上隐藏键盘。在这里尝试了所有方法及其组合。不可能。显示它的方法有效,但无论什么 windw 令牌、隐藏旗帜、清单设置或蜡烛给任何圣徒,我都无法隐藏它。在键盘显示中,我总是看到这个: I/LatinIME( 396): 指定InputType.TYPE_NULL W/LatinIME( 396): 意外的输入类: inputType=0x00000000 imeOptions=0x00000000
5赞 Harshal Benake 1/13/2014
/** * 此方法用于隐藏软键盘。* @param活动 */ public void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager)activity.getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); }
0赞 nmxprime 6/20/2014
这对我有用
0赞 Ready Android 5/4/2018
需要使用 InputMethodManager 和INPUT_METHOD_SERVICE来处理软键盘,就像 readyandroid.wordpress.com/show-hide-android-soft-keyboard

答:

4705赞 15 revs, 15 users 21%Reto Meier #1

您可以使用 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 语法

// Only runs if there is a view that is currently focused
this.currentFocus?.let { view ->
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    imm?.hideSoftInputFromWindow(view.windowToken, 0)
}

评论

2赞 capo11 5/26/2021
现在需要 a 和 serviceClass 。对于上下文,我可以调用,但是对于serviceClass呢?getSystemService()ContextClassrequiredContext
1赞 Windgate 9/8/2021
@capo11我尝试使用Application.Context.getSystemService(),所以我不需要serviceClass,但它不起作用
0赞 Captain Jack Sparrow 6/29/2022
对我来说效果很好,在使用FragmentgetActivity().getSystemService()...
166赞 5 revs, 5 users 48%Jeyavel #2

请尝试以下代码onCreate()

EditText edtView = (EditText) findViewById(R.id.editTextConvertValue);
edtView.setInputType(InputType.TYPE_NULL);

评论

3赞 Spike Williams 4/17/2010
此方法可作为解决 2.0 和 2.1 中“无法隐藏软键盘”错误的方法,如 code.google.com/p/android/issues/detail?id=7115 中所述......上面列出的hideSoftInputFromWindow方法在我尝试时不起作用,但editView.setInputType(0)可以。
22赞 Bostone 10/12/2010
根据 Javadoc(不是黑客),这是合法的,尽管我会将方法重写为editView.setInputType(InputType.TYPE_NULL);
3赞 Tirtha 1/11/2012
这有效,但是,它隐藏了android:hint。我使用的是 Android 1.5
0赞 Stefan Brendle 8/9/2016
它有效,但它也隐藏了光标。我需要光标,但没有系统键盘。
0赞 General Grievance 3/23/2022
答案的第二部分是从另一个答案复制而来的。修订版已回滚。
854赞 5 revs, 4 users 50%Garnet Ulrich #3

隐藏软键盘也很有用:

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

这可用于禁止使用软键盘,直到用户实际触摸 editText 视图。

评论

0赞 Brian M 12/13/2020
这是 2020 年唯一有效的一个。我在主活动上有编辑文本,不希望在启动应用程序时出现键盘。
0赞 Pragnesh Ghoda シ 2/28/2023
尝试使用 InputMethodManager 来处理键盘。可以尝试按照这篇文章进行操作。androidacademic.blogspot.com/2023/02/......
170赞 3 revs, 3 users 64%mckoss #4

Meier的解决方案也适用于我。就我而言,我的应用程序的顶层是一个选项卡主机,我想在切换选项卡时隐藏关键字 - 我从选项卡主机视图获取窗口令牌。

tabHost.setOnTabChangedListener(new OnTabChangeListener() {
    public void onTabChanged(String tabId) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(tabHost.getApplicationWindowToken(), 0);
    }
}
157赞 3 revsNguyen Minh Binh #5

更新:我不知道为什么这个解决方案不再起作用了(我刚刚在 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);

评论

8赞 user2236096 7/16/2013
我应该把这个代码放在哪里?我尝试粘贴getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);在 onCreate() 中,但键盘永远不会隐藏
0赞 syr 8/7/2015
不起作用,在 radioGroup.setOnCheckedChangeListener、API 23 中测试
0赞 Palejandro 8/18/2016
如果仔细观察,InputMethodManager.HIDE_IMPLICIT_ONLY 和 InputMethodManager.SHOW_IMPLICIT 的值相同,即“1”,因此这些调用之间没有区别。=>不工作
0赞 Duna 11/29/2016
如果调用 imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);然后键盘将显示在屏幕上:)最佳实现是:Android SDK 上的 github.com/ravindu1024/android-keyboardlistener Shame
0赞 King King 12/16/2016
I don't know why this solution is not work any more- 因为它是 Android,一切都会改变,也许部分是糟糕的设计......我们粗心大意地写,然后我们删除所有内容并重写所有内容。
21赞 Peter Ajtai #6

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

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

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

在继续之前,请确保暂停一会儿,因为关闭后退按钮需要一段时间,因此在短暂的暂停(1 秒足够长的 ime)之前,不会记录对视图等的后续单击。

88赞 3 revs, 2 users 81%Rotemmiz #7

如果这里的所有其他答案都不能像您希望的那样适合您,还有另一种手动控制键盘的方法。

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

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

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

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

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);

评论

0赞 gimmegimme 3/1/2017
我在第二段代码的第 7 行和第 10 行收到“无法解析符号上下文”。
0赞 Rotemmiz 3/1/2017
请改用 getContext()
0赞 AgungCode.Com 3/10/2022
上下文上下文 = View.getContext();
66赞 2 revs, 2 users 80%shontauro #8

通过这样的搜索,在这里我找到了一个适合我的答案

// 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);
389赞 3 revs, 3 users 80%Saurabh Pareek #9

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

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

这里在 的位置和 的位置传递。它将强行关闭软键盘。HIDE_IMPLICIT_ONLYshowFlag0hiddenFlag

评论

6赞 Alex 3/23/2013
您在 showflags 参数中使用了隐藏标志。这之所以有效,是因为常量使用相同的整数。使用正确标志的示例
38赞 Sver 8/30/2013
@Mark:因为该方法名为“toggleSoftInput”,而不是“hideSoftInput”:)
2赞 Rohaitas Tanoli 9/3/2021
这无法正常工作。它有时会显示键盘。
49赞 sergio91pt #10

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

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

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
    }
}

对于旧版本,我得到了非常好的结果(但远非完美),在我的根视图的帮助下添加了一个,然后检查键盘是否显示如下:OnGlobalLayoutListenerViewTreeObserver

@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);

评论

0赞 halxinate 3/27/2013
很酷的解决方案,但是,如果您的前部活动不是全屏的,则键盘在其后面可见。此外,键盘的光标移动辅助工具也仍然可见。而且它不能被剥皮。
0赞 olefevre 12/21/2015
我附议。在所有可能的方法中,只有 getWindow().setFlags() 方法有效,至少在 Android 5.1 上是这样。请注意,setSoftInputShownOnFocus() 现在是 setShowSoftInputOnFocus(),不再隐藏但不起作用,至少在用户触摸字段时不起作用。
104赞 5 revs, 5 users 43%Sreedev R #11
protected void hideSoftKeyboard(EditText input) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(input.getWindowToken(), 0);    
}

评论

5赞 ymerdrengene 4/10/2014
这对我有用!但是你为什么要把input.setInputType(0)?当我有那行代码时,我无法与 EditTextView 交互(当我删除它时它起作用)。
0赞 CoolMind 9/19/2018
可能。input.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)
0赞 CoolMind 11/28/2018
我从这段代码中删除了。它改变了键盘行为,并且 .input.setInputType(0);inputTypeEditText
18赞 Ian Vink #12

以下是在 Mono for Android(又名 MonoDroid)中执行此操作的方法

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

评论

1赞 PCoder 11/27/2012
片段中有什么?searchbox
8赞 jasonhudgins #13

您还可以考虑在 EditText 上使用 setImeOption

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

评论

0赞 Lassi Kinnunen 9/27/2012
在这种方法中,有什么技巧可以使键盘自动关闭吗?它没有在 JellyBean 上这样做。edittext 会失去焦点,但键盘不会隐藏。
22赞 2 revs, 2 users 76%Ash #14

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

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();
}
8赞 2 revs, 2 users 75%Agilanbu #15

有时,您想要的只是 Enter 按钮来折叠您拥有的属性框keyboardEditText

 android:imeOptions="actionDone" 

这会将“Enter”按钮更改为“完成”按钮,该按钮将关闭键盘。

评论

1赞 tmr 10/25/2014
就我而言,除了还需要包括android:imeOptions="actionDone"android:singleLine="true"
2赞 Phil #16

我部分从 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);
    }   
}
11赞 2 revs, 2 users 78%tommy chheng #17

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

使用 InputMethodManager 不会关闭键盘。我必须清除焦点并将搜索视图的可聚焦设置为false:

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

评论

1赞 Alex 3/23/2013
非常聪明。如果用户想要再次搜索,只需再次单击搜索即可。
0赞 Azurespot 7/7/2014
SearchView 在 Android API 页面中没有,所以这对我不起作用,但另一种解决方案可以(请参阅下面的答案)。clearFocus()
0赞 Yousha Aleayoub 4/19/2016
@Noni A,stackoverflow.com/questions/7409288/......
73赞 2 revsAlex #18

到目前为止,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 ... */
}
33赞 2 revs, 2 users 93%Luke Sleeman #19

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

您可以在我的应用程序干净 RPN 中看到它的工作实现。

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

  1. 暂时隐藏键盘。当用户 聚焦新的文本字段。
  2. 活动开始时显示键盘 并在活动上设置一个标志,指示他们应 始终可见。仅当活动 正在初始化。
  3. 将活动标记为从不显示或允许使用 键盘。仅当活动 正在初始化。

对我来说,暂时隐藏键盘是不够的。在某些设备上,一旦聚焦新的文本字段,它就会重新出现。由于我的应用在一个页面上使用多个文本字段,因此聚焦新的文本字段将导致隐藏的键盘再次弹出。

遗憾的是,列表中的第 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 4 的 2.2 岁的 HTC 手机到运行 4.2.2 的 nexus 7。这种方法的唯一缺点是您需要小心处理后退按钮。由于我的应用程序基本上只有一个屏幕(它是一个计算器),我可以覆盖 onBackPressed() 并返回设备主屏幕。

评论

2赞 rupps 5/15/2013
精心设计的解决方法,但我认为这太过分了,为了隐藏键盘而重新创建数千个对象。我不知道是谁为 android 设计了 IMM,但它闻起来像 Windows APi。在我看来,一个好的 IME 应该有两种方法:隐藏和显示:-)
1赞 Luke Sleeman 5/20/2013
这都是真的,但我的解决方法确实有一个优势 - 它总是有效!我找不到其他解决方案可以始终切换键盘,无论 UI 中的哪些字段具有焦点、用户对切换和键盘做了什么以及他们正在运行的 android 版本如何:-\
0赞 rupps 5/20/2013
伙计,我完全不顾一切地想把键盘藏起来。尝试了数千种东西,noooone 有效。但是您的解决方法对我来说太多了,我必须重新创建 10 个片段,初始化服务,删除很多 WeakReferences ....你知道的?GC 会扔掉 25mb :S ...仍在寻找一种可靠的方法来做到这一点:(
0赞 rupps 10/9/2013
@Dmitry好吧,这不是一个你好的世界......对于平板电脑来说,这是一个复杂的应用程序。我拒绝从内存中完全卸载它,只是为了隐藏一个愚蠢的键盘......无论如何,我找到了一些可以结合这里提出的一千种解决方案的方法:)
12赞 Sagar Maiyad #20
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;
    }
});

评论

0赞 zmicer 11/7/2013
也试试这个 - 这对我有用: InputMethodManager imm = ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE));imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
2赞 rupps #21

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

然后突然我发现了一个明显成功的组合:

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

结合您常用的食谱

blahblaj.hideSoftInputFromWindow ...

希望这能阻止有人自杀......我离它很近。当然,我不知道它为什么会起作用。

2561赞 15 revs, 10 users 60%rmirabelle #22

为了帮助澄清这种疯狂,我想首先代表所有 Android 用户为 Google 对软键盘的彻头彻尾的荒谬处理道歉。对于同一个简单的问题,之所以有这么多答案,每个答案都不同,是因为这个 API 和 Android 中的许多其他 API 一样,设计得很糟糕。我想不出任何礼貌的方式来表达它。

我想隐藏键盘。我希望为 Android 提供以下声明:.结束。谢谢。但是Android有一个问题。您必须使用 隐藏键盘。好的,好的,这是 Android 的键盘 API。但!您需要拥有 IMM 才能访问 IMM。现在我们有一个问题。我可能想从没有任何用处或不需要任何的静态或实用程序类中隐藏键盘。或者更糟糕的是,IMM 要求您指定要隐藏键盘的内容(甚至更糟的是,内容)。Keyboard.hide()InputMethodManagerContextContextViewWindow

这就是隐藏键盘如此具有挑战性的原因。亲爱的谷歌:当我查找蛋糕的食谱时,地球上没有人会拒绝向我提供食谱,除非我首先回答蛋糕将被谁吃掉以及在哪里吃!!RecipeProvider

这个悲伤的故事以丑陋的事实结束:要隐藏 Android 键盘,您需要提供 2 种形式的身份证明:a 和 a 或 a .ContextViewWindow

我创建了一个静态实用程序方法,只要您从 .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);
}

请注意,此实用程序方法仅在从 !上述方法调用目标以获取正确的窗口令牌。ActivitygetCurrentFocusActivity

但是,假设您想将键盘隐藏在 ?您不能使用上述方法:EditTextDialogFragment

hideKeyboard(getActivity()); //won't work

这是行不通的,因为您将传递对 的 host 的引用,该主机在显示时没有集中的控制!哇!因此,为了隐藏键盘的碎片,我求助于较低级别、更常见且更丑陋的:FragmentActivityFragment

public static void hideKeyboardFrom(Context context, View view) {
    InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

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

关于windowSoftInputMode

还有另一个争论点需要注意。默认情况下,Android 会自动将初始焦点分配给 .自然而然地,InputMethod(通常是软键盘)将通过显示自身来响应焦点事件。当 中的属性设置为 时,指示键盘忽略此自动分配的初始焦点。EditTextActivitywindowSoftInputModeAndroidManifest.xmlstateAlwaysHidden

<activity
    android:name=".MyActivity"
    android:windowSoftInputMode="stateAlwaysHidden"/>

几乎令人难以置信的是,当您触摸控件时,它似乎没有执行任何操作来阻止键盘打开(除非和/或分配给控件)。显然,windowSoftInputMode 设置仅适用于自动焦点事件,而不适用于由触摸事件触发的焦点事件。focusable="false"focusableInTouchMode="false"

因此,确实命名得很差。也许应该改用它。stateAlwaysHiddenignoreInitialFocus


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

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

这些是上述代码的替代方法:这些代码不明确引用您的活动。if (view == null) view = new View(activity);

在 fragment 类中:

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

给定一个片段作为参数:fragment

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

从内容正文开始:

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

更新2:清除焦点以避免在从后台打开应用程序时再次显示键盘

将以下行添加到方法的末尾:

view.clearFocus();

评论

1赞 ilw 12/15/2020
为什么需要,为什么不只?getRootView()getView()
5赞 Martin Braun 4/10/2021
一班:((InputMethodManager)getContext().getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getView().getWindowToken(), 0);
1赞 gmk57 5/21/2021
最近,我们终于得到了一种官方的、向后兼容的方式来做到这一点
1赞 Sergey Chilingaryan 5/25/2021
最后,有一个官方的方式 stackoverflow.com/a/67683124/4985958
0赞 Marcell 6/11/2022
我对此有一个问题。EditText 字段中的文本将保持下划线,就好像键盘的建议仍处于活动状态一样。
12赞 Atish Agrawal #23

使用这个

this.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
31赞 4 revs, 2 users 82%Saran #24

或者,如果您想从任何位置关闭软键盘,而不引用用于打开键盘的 (EditText) 字段,但仍希望在该字段处于焦点状态时执行此操作,则可以使用此(来自 Activity):

if (getCurrentFocus() != null) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
50赞 3 revsslinden77 #25

这应该有效:

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);

评论

0赞 slinden77 7/15/2016
@YoushaAleayoub是的,它会的。KeyBoard.toggle(fragment.getActivity())
0赞 Yousha Aleayoub 7/17/2016
@slinden77,哈哈,我说的是你的答案......不是你评论的这个。所以这个答案仍然行不通。
0赞 slinden77 7/18/2016
@YoushaAleayoub呃,是的,它会的。原来的问题没有提到碎片,你是提到碎片的人。所以我的回答是完全有效的。要将其与片段一起使用,请以不同于 的方式调用该方法,例如注释。请学习如何使用方法,然后回来。你用你愚蠢的回复让人们感到困惑Fragment
2赞 Gaurav Arora #26

这种方法将始终不惜一切代价起作用。只需在您想隐藏键盘的任何地方使用它

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的版本是什么。这种方法肯定会奏效

-6赞 2 revs, 2 users 98%Siddharth_Vyas #27

这对我有用:

 @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;
}
6赞 3 revsSandeep Maram #28

它对我有用..

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

将 onClick() 中的代码行放在下面

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

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

(或)

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
17赞 4 revs, 3 users 89%Pinhassi #29

这对我所有奇怪的键盘行为都有效

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);
    }
}

评论

0赞 justdan0227 11/29/2018
什么是 mRootView?
2赞 Jacek Kwiecień #30
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"

3赞 2 revs, 2 users 86%moberme #31

这对我有用。

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);
}
15赞 2 revs, 2 users 75%Hamid FzM #32

只需在 Activity 中使用此优化的代码:

if (this.getCurrentFocus() != null) {
    InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
2赞 2 revs, 2 users 79%Noni A. #33

另一种方法是使用以下代码: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 搜索框,当提交查询中的文本(用户按任一键或搜索按钮/图标)时,代码将被激活并使软键盘关闭。这段代码被放在我的. 是 的默认代码的一部分。感谢 @mckoss 提供了大量代码!EnterInputMethodManageronCreateOptionsMenu()searchItemMenuItemonCreateOptionsmenu()

64赞 3 revsAlex.F #34

简短的回答

在侦听器中调用OnClickonEditorActionEditTextIME_ACTION_DONE

button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        someEditText.onEditorAction(EditorInfo.IME_ACTION_DONE)
    }
});

向下钻取

我觉得这种方法更好、更简单,更符合 Android 的设计模式。 在上面的简单示例中(通常在大多数常见情况下),您将有一个具有/具有焦点的键盘,并且它通常也是首先调用键盘的那个(在许多常见情况下,它绝对能够调用它)。同样,它应该是释放键盘的那个,通常可以通过 .看看 with 的行为,你想用同样的方式实现同样的行为。EditTextImeActionEditTextandroid:imeOptions="actionDone"


查看此相关答案

4赞 Vaishali Sutariya #35
public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager) activity
            .getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
            .getWindowToken(), 0);
}

评论

1赞 Vladimir Petrakovich 8/27/2014
好答案,但可以返回activity.getCurrentFocus()null
2赞 Duna #36
private void hideSoftKeyboard() {
    View view = getView();
    if (view != null) {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
                .getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}
2赞 Geng Jiawen #37

抛开所有这些答案,为了简单起见,我写了一个常用的方法来做到这一点:

/**
 * 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);
    }
}
14赞 3 revs, 2 users 78%injecteer #38

我有这种情况,我的也可以位于 ,所以键盘应该在关闭时关闭。以下代码似乎在任何地方都可以使用:EditTextAlertDialog

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 );
}

评论

1赞 Billyjoker 2/12/2015
此解决方案更好,因为您不必控制将哪个 EditText 作为参数传递给 hideSoftInputFromWindow() 方法。效果很好!!
4赞 2 revs, 2 users 71%Sagar Badave #39

试试这个

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);
    }
}
14赞 Girish Patel #40

对于打开键盘:

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);
0赞 nobjta_9x_tq #41

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

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;

        }
    });
11赞 ahmed_khan_89 #42

我几乎尝试了所有这些答案,我遇到了一些随机问题,尤其是三星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);
}
38赞 shobhan #43
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);
    }
}
26赞 2 revsban-geoengineering #44

多亏了这个 SO 答案,我得出了以下内容,就我而言,在滚动浏览 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);
    }
}
6赞 Ricardo #45

有时,您可以有一个包含列表视图的活动,其中包含包含 editText 的行,因此您必须在清单中进行设置,然后它们会出现键盘,这很烦人。SOFT_INPUT_ADJUST_PAN

如果您将以下工作圈放在onCreate

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);
6赞 user3846697 #46

在设置下AndroidManifest.xml<activity..>android:windowSoftInputMode="stateAlwaysHidden"

4赞 Adnan Abdollah Zaki #47

简单代码: 在 onCreate() 中使用此代码

getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);
11赞 iscariot #48

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

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);
        }
    }
}
15赞 NickUnuchek #49

添加到清单文件中的活动。例:android:windowSoftInputMode="stateHidden"

<activity
            android:name=".ui.activity.MainActivity"
            android:label="@string/mainactivity"
            android:windowSoftInputMode="stateHidden"/>
2赞 ceph3us #50
/** 
 *
 *   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);
}
4赞 Thiago #51

简单的方法伙计们: 试试这个...

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);
        }
    }
6赞 2 revs, 2 users 92%user3102913 #52

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

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

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

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

评论

0赞 Rock Lee 5/25/2016
当我用打开键盘的视图替换 fEmail 时,java 代码解决方案在片段中为我工作。它适用于运行 Android 2 的三星 Galaxy Tab S5.1.1、运行 5 的 Nexus 6.0.1 和运行 5.1 的 XT1032(这是使用支持库。
1赞 Heena Arora #53

用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();
}
1赞 Mansuu.... #54

您只需在清单活动标记中写入一行

 android:windowSoftInputMode="stateAlwaysHidden|adjustPan"

它会起作用的。

16赞 Naveed Ahmad #55

简单易用的方法,只需调用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);
}

评论

0赞 Adam Burley 6/7/2022
您没有检查是否为 null,如果键盘实际上不可见,则很可能是activity.getCurrentFocus()
4赞 2 revsvicky patel #56
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;
                    }
                });
14赞 Giedrius Šlikas #57

每次都像魔术一样工作

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);
    }
}
1赞 JamesC #58

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

在我的项目中,我动态地创建了一个对话框(通过在不使用或使用最少的 XML 的情况下对其进行编程)。AlertDialog

所以我在做这样的事情:

    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();

在玩弄了所有答案之后,我发现如果您知道在哪里提出请求,它们中的大多数都有效......这是所有事情的关键。

所以,诀窍是把它放在创建对话框之前:就我而言,这就像魅力一样: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..)

我很确定这个原则对所有窗口都是相同的,所以要注意你的“showKeyboard”代码的位置 - 它应该在窗口启动之前。

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

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

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

6赞 Vishal Yadav #59

试试这个

  • 简单,你可以调用你的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);

6赞 tech.mohit.garg #60

这是工作..

只需在函数中传递当前活动实例

 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
    }
}
1赞 Kavin Varnan #61

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);

评论

1赞 Victor Rendina 2/6/2018
创建一个扩展函数似乎是一个不错的方法Activityfun Activity.closeKeyboard() { (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).apply { hideSoftInputFromWindow(window.decorView.windowToken, 0) } }
3赞 uma #62

你可以简单地将此代码添加到你想隐藏软键盘的位置。

                        // 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);
                            }
4赞 Fakhriddin Abdullaev #63

这是最好的解决方案

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

<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" />

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

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

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

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

InputMethodManager imm = (InputMethodManager) 
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 
InputMethodManager.HIDE_NOT_ALWAYS);
6赞 2 revsJanusz Hain #64

如果有人有兴趣,我已经为 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”Application 对象

更新:在某些情况下,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
3赞 Nadeem Bhat #65

在 Android 中,要通过 InputMethodManage 隐藏 Vkeyboard,可以通过传入包含焦点视图的窗口的令牌来 cal hideSoftInputFromWindow。

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甚至可以工作

3赞 Harpreet #66

如果应用程序面向 API 级别 21 或更高级别,则使用默认方法:

editTextObj.setShowSoftInputOnFocus(false);

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

<EditText  
    ....
    android:enabled="true"
    android:focusable="true" />
1赞 Rafols #67

一些 kotlin 代码:

在“活动”中隐藏键盘:

(currentFocus ?: View(this))
            .apply { (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
                        .hideSoftInputFromWindow(windowToken, 0) }
4赞 Daniel Beltrami #68

非常简单的方法

我在我所有的项目中都是这样做的,并且像做梦一样工作。在您的声明中,只需添加以下一行: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>
2赞 Jedsada Tiwongvorakul #69

您可以为任何视图创建扩展函数

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

与 Activity 一起使用的示例

window.decorView.hideKeyboard();

与 View 一起使用的示例

etUsername.hideKeyboard();

祝您编码愉快...

5赞 2 revs, 2 users 98%Ready Android #70

实际上,Android 权威总是提供新的更新,但他们没有处理所有 Android 开发人员在开发中面临的旧缺点,默认情况下,这应该由 Android 权威处理,在从 EditText 更改焦点时,应该隐藏/显示软输入键盘选项。但很抱歉,他们没有管理。好吧,离开它。

以下是在 Activity 或 Fragment 中显示/隐藏/切换键盘选项的解决方案。

显示视图的键盘:

/**
 * 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();
    }
}

使用 Fragment 上下文显示键盘:

/**
 * 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();
    }
}

使用 Fragment 上下文隐藏键盘:

/**
 * 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();
    }
}
5赞 Qamar #71

在 Kotlin 中

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)
    }
1赞 jBegera #72

我正在使用以下 Kotlin Activity 扩展:

/**
 * 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)
    }
}
3赞 2 revs, 2 users 99%Rishabh Saxena #73

当您想在按钮单击操作时手动隐藏键盘时:

/**
 * 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();
    }
}

当您想在单击屏幕时隐藏键盘时,编辑文本除外在 Activity 中覆盖此方法:

@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);
}
1赞 2 revsDmitry #74

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

        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);
1赞 mr5 #75

对于 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);
}
5赞 2 revsKhemraj #76

这里有隐藏和显示方法。

Kotlin

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)
}

爪哇岛

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);
}
0赞 The Bala #77

在 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);
}
1赞 Umesh Maharjan #78
 fun hideKeyboard(appCompatActivity: AppCompatActivity) {
        val view = appCompatActivity.currentFocus
        val imm = appCompatActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }
0赞 Coldfin Lab #79
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);
}
2赞 Phil #80

Kotlin 中的 Wiki 答案:

1 - 在文件(例如,包含所有顶级函数的文件)内创建一个顶级函数

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()
5赞 Rajneesh Shukla #81

调用此方法隐藏软键盘

public void hideKeyBoard() {
    View view1 = this.getCurrentFocus();
    if(view!= null){
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view1.getWindowToken(), 0);
    }
}
2赞 2 revsshrewdu #82

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

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

把它放在一个名为 ViewExtensions(或你有什么)的文件中,并像普通方法一样在您的视图上调用它。

6赞 Krasavello13 #83

如果您使用 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)
    }
}

对于 Fragment:

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)
        }
    }
}

现在,您可以简单地调用 Fragment 或 Activity:

 hideKeyboard()

评论

0赞 luckyhandler 7/15/2020
与其再次编写相同的逻辑,只需调用 activity?。hideKeyboard 从片段实现
0赞 luckyhandler 7/15/2020
顺便说一句,片段实现并不像社区 wiki 所说的那样工作。若要获取正确的 windowToken,必须调用 val windowToken = view?。rootView?。window令牌
1赞 hardiBSalih #84

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

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

}

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

<activity
    android:name=".Activity.MainActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar"
    android:windowSoftInputMode="stateAlwaysHidden">
2赞 Ambilpura Sunil Kumar #85
there are two ways to do so...

method 1:in manifest file

define the line **android:windowSoftInputMode="adjustPan|stateAlwaysHidden"** of code in your manifest.xml file as below...

<activity
            android:name="packagename.youactivityname"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustPan|stateAlwaysHidden" />

Method 2 : in Activity or Java class

 if(getCurrentFocus()!=null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)`enter code here`;
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }

它会work....@ASK

3赞 Arihant Jain #86

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

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)
        }

    }

}

使用一行代码从任意位置调用 Above 方法。

CustomSnackbar.hideKeyboard(view, this@ActivityName)

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

评论

0赞 portfoliobuilder 7/30/2019
Context.INPUT_METHOD_SERVICE和Activity.INPUT_METHOD_SERVICE有什么区别吗?两者似乎都有效
0赞 portfoliobuilder 7/30/2019
此外,您的代码示例将抛出 IllegalStateException
0赞 Arihant Jain 7/30/2019
@portfoliobuilder你认为它会在哪里抛出异常?
0赞 portfoliobuilder 7/31/2019
假设用户执行标准实现,即在应用进入后台时隐藏键盘 (onPause),并在前台显示键盘 (onResume)。现在让我们也假设两个屏幕。如果键盘已隐藏,并且从活动 A 到活动 B(或片段 A 到片段 B,或活动 A 到片段 B 等)的转换,则可能发生 illegalStateException。您无需检查键盘是否已经可见。
3赞 Priyanka #87

只需在 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);
}
1赞 Selman Tosun #88

此代码片段可以提供帮助:

    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...

2赞 Udara Abeythilake #89

首先,您应该从 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;
    }
});
2赞 Nikhil Katekhaye #90

这对我来说是工作。它在 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)
        }
    }
5赞 4 revs, 3 users 56%Bhavik Nathani #91

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

<activity
    android:name=".MainActivity"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="adjustPan"/>
2赞 2 revs, 2 users 50%KarlTheGreat #92

一个简单的解决方法是只使用 Button 方法。editText.setEnabled(false);editText.setEnabled(true);onClick()

1赞 2 revs, 2 users 69%Rahul Patil #93

试这个

完全强制使用Android软输入键盘:

在帮助器类中创建方法

InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
3赞 6 revs, 4 users 71%Salman Nazir #94

我使用 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)
}
1赞 2 revs, 2 users 75%norbDEV #95

这适用于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)
}

评论

0赞 Peter Mortensen 10/18/2023
什么?科特林
-1赞 2 revs, 2 users 57%Marium Jawed #96

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

android:imeOptions="actionDone"
7赞 2 revs, 2 users 80%Sanket Naik #97

适合 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)
    }
}
-10赞 3 revs, 3 users 73%Abdullah Nagori #98

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

android:focusable="false"

评论

15赞 SMBiggs 1/20/2020
你只是在扔飞镖,而这个飞镖不仅错过了棋盘,还差点撞到酒保。
8赞 3 revs, 3 users 84%Junaid Bashir #99

只需调用以下方法即可。如果它显示,它将隐藏您的键盘。

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) {
    }
}
3赞 2 revs, 2 users 72%Kalpesh Rupani #100

通过将泛型方法添加到实用程序或帮助程序类中。只需调用自身,即可隐藏和显示键盘:

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)
}
1赞 2 revs, 2 users 86%Davinder Goel #101

您也可以使用此代码片段在 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)
 }
4赞 Leonid Ivankin #102

从一个片段移动到另一个片段时

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()
}

评论

0赞 Peter Mortensen 10/18/2023
科特林
16赞 2 revs, 2 users 89%aminography #103

通过扩展功能的 Kotlin 版本

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

扩展函数.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)
}

用法

现在在 ur or 中,可以清楚地访问它,也可以从以下实例中调用它:ActivityFragmenthideKeyboard()EditText

editText.hideKeyboard()
2赞 Gastón Saillén #104

Kotlin

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)
7赞 2 revs, 2 users 79%Pankaj Kumar #105

使用 Android 10,我们将获得一种显示和隐藏键盘的惊人方式。阅读发行说明 - 1.5.0-alpha02。现在如何隐藏或显示键盘:

val controller = view.windowInsetsController

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

链接我自己的答案 如何在Android中检查软件键盘的可见性? 以及一个惊人的博客,其中包含更多这种变化(甚至比它更多)。

评论

0赞 Michael Abyzov 2/20/2021
什么是导入?Type
0赞 Pankaj Kumar 2/20/2021
@MichaelAbyzov这将是 'developer.android.com/reference/android/view/WindowInsets.Type',请参阅有关 hide() 方法的更多信息,请参阅“developer.android.com/reference/kotlin/android/view/...'
1赞 2 revs, 2 users 89%Jaydeep chatrola #106

Android 11 中有一个名为 .应用程序可以从任何视图访问控制器,通过该视图,我们可以使用 和 方法:WindowInsetsControllerhide()show()

val controller = view.windowInsetsController

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

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

请参阅 WindowInsetsController

1赞 Md. Masum Billah #107
 //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);
        }
```
2赞 2 revs, 2 users 74%Ayan Bhattacharjee #108

这个对我有用。你只需要在里面传递元素。

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(AutocompleteviewDoctorState.getWindowToken(), 0);
1赞 2 revs, 2 users 59%niek tuytel #109

如果你在android:focused=“true”中设置,那么它将不起作用,因为它是一个不可更改的集合。.xml

所以解决方案:

android:focusedByDefault=“true”

然后它会设置一次,可以隐藏或显示键盘。

6赞 2 revs, 2 users 87%Mattia Ferigutti #110

片段中的 Kotlin 解决方案

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)
        }
}

检查清单中是否没有与活动关联的此参数:

android:windowSoftInputMode="stateAlwaysHidden"
0赞 2 revs, 2 users 67%Abrar Malekji #111

有很多答案。如果毕竟没有任何效果,那么这里有一个提示:),

您可以制作一个 EditText 和

edittext.setAlpha(0f);

由于 alpha 方法,将看不到此 edittext。 现在使用上面关于如何使用 EditText 显示/隐藏软键盘的答案。

4赞 Anubhav #112

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

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
4赞 4 revs, 2 users 84%Rizwan Ahmed #113

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

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

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

这是您当前的观点。view

1赞 Miles Morales #114

以下是使用 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 )
}
36赞 3 revs, 2 users 67%gmk57 #115

现在,差不多 12 年后,我们终于有一种官方的、向后兼容的方式来与 AndroidX Core 1.5+ 做到这一点:

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

或专门针对 Fragment:

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

评论

8赞 rmirabelle 5/22/2021
好吧,你会看看吗!当然,它必须涉及另一个 API(窗口插图控制器与输入法管理器),但嘿,至少“隐藏”这个词在那里。
1赞 Mark 8/8/2021
如果要隐藏键盘,但仅引用 Activity,则应使用哪个视图? ?在此之前,您将获取 windowToken,然后使用window.decorViewcurrentFocus?.windowTokenInputMethodManager.hideSoftInputFromWindow(windowToken, 0)
1赞 gmk57 8/23/2021
@Mark,问得好!测试表明,这在 API 25-29 上不起作用:返回 。 在 API 30 上也有类似的问题。但是您可以在布局中使用任何视图,例如其根视图。对于隐藏键盘,它可以工作,但是对于显示键盘,您可能最好使用一些:使用它来请求焦点。window.decorViewViewCompat.getWindowInsetsController()nullcurrentFocusEditTextWindowInsetsControllerCompat.show()
0赞 Mark 8/25/2021
谢谢@gmk57那么使用 pre-30 和 30+ 怎么样?currentFocuswindow.decorView
0赞 gmk57 8/26/2021
这可能有效,但无论如何,您都必须对其进行彻底测试。行为可能取决于设备制造商、您的特定小组件布局和其他因素。例如,在我的一台设备上,这种显示键盘的方法适用于 GBoard,但完全禁用了 SwiftKey。这是Android。:(
1赞 Mark 8/26/2021
@gmk57很高兴知道谢谢。因此,听起来最好在活动的 View 层次结构中使用 View(通常我可以访问 )。从 a 中,只需使用 .但是,我没有看到使用有任何好处SomeBinding.rootFragmentview?.hideKeyboard()context.getSystemService<InputMethodManager>()?.hideSoftInputFromWindow(windowToken, 0)
1赞 mirij #116

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

48赞 7 revs, 4 users 58%Sergey Chilingaryan #117

感谢上帝,它在 11 年后得到了官方支持。

首先,将依赖项添加到应用 gradle。implementation 'androidx.core:core-ktx:1.7.0'

然后从 ViewCompat 或 WindowCompat 类获取 InsetsController。

最后使用 InsetsController 的 hide() 和 show() 函数

添加对 Dialog 的支持。在 BottomSheetDialog 中可用。@Rondev。 使用更安全的方式获取活动,而不是直接从上下文中强制转换。

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.ContextWrapper
import android.view.View
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment

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

fun Dialog.showKeyboard() = window?.decorView?.showKeyboard()
fun Dialog.hideKeyboard() = window?.decorView?.hideKeyboard()

fun Context.showKeyboard() = getActivity()?.showKeyboard()
fun Context.hideKeyboard() = getActivity()?.hideKeyboard()

fun Fragment.showKeyboard() = activity?.showKeyboard()
fun Fragment.hideKeyboard() = activity?.hideKeyboard()

fun Activity.showKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.show(WindowInsetsCompat.Type.ime())
fun Activity.hideKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.hide(WindowInsetsCompat.Type.ime())

fun Context.getActivity(): Activity? {
    return when (this) {
        is Activity -> this
        is ContextWrapper -> this.baseContext.getActivity()
        else -> null
    }
}

下面的旧 anwser

这是github上的简单项目

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.ContextWrapper
import android.view.View
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment

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

fun Dialog.showKeyboard() = window?.decorView?.showKeyboard()
fun Dialog.hideKeyboard() = window?.decorView?.hideKeyboard()

fun Context.showKeyboard() = getActivity()?.showKeyboard()
fun Context.hideKeyboard() = getActivity()?.hideKeyboard()

fun Fragment.showKeyboard() = activity?.showKeyboard()
fun Fragment.hideKeyboard() = activity?.hideKeyboard()

fun Activity.showKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.show(WindowInsetsCompat.Type.ime())
fun Activity.hideKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.hide(WindowInsetsCompat.Type.ime())

fun Context.getActivity(): Activity? {
    return when (this) {
        is Activity -> this
        is ContextWrapper -> this.baseContext.getActivity()
        else -> null
    }
}

评论

3赞 Johann 11/23/2021
需要 API 级别 31
0赞 Sergey Chilingaryan 11/23/2021
@Johann 为了实现兼容性,请使用 WindowCompat 和 WindowInsetsControllerCompat。您需要将 androidx.core 的 gradle 依赖项至少升级到 1.6.0-alpha03,以便对 SDK < 30 提供支持。
0赞 Sergey Chilingaryan 12/9/2021
@Johann看一下示例项目 github.com/sergchil/KeyboardTest
2赞 Rondev 1/23/2022
不幸的是,我无法让隐藏函数在BottomSheetDialogFragment
3赞 Muhammad Babar 2/16/2023
getWindowInsetsController 已弃用
0赞 Yogesh Sarvaiya #118
public final class UtilsKeyboard {
/**
 * Sets the cursor at the end of this edit text and shows a keyboard
 */
public static void focusKeyboard(@NonNull EditText editText) {
    editText.requestFocus();
    editText.setSelection(editText.getText().length());
    showKeyboard(editText);
}

private static void showKeyboard(@NonNull View view) {
    final InputMethodManager manager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    if (manager != null) {
        manager.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }
}

public static boolean hideKeyboard(@NonNull Window window) {
    View view = window.getCurrentFocus();
    return hideKeyboard(window, view);
}

private static boolean hideKeyboard(@NonNull Window window, @Nullable View view) {
    if (view == null) {
        return false;
    }
    InputMethodManager inputMethodManager = (InputMethodManager) window.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null) {
        return inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
    return false;
}

public static boolean hideKeyboard(@Nullable View view) {
    if (view == null) {
        return false;
    }
    InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null) {
        return inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
    return false;
}

/**
 * This will hide the keyboard and unfocus any focused view.
 */
public static void unfocusKeyboard(@NonNull Window window) {
    // When showing the bottom menu, make sure the keyboard isn't and that no view has focus
    hideKeyboard(window);
    final View focused = window.getCurrentFocus();
    if (focused != null) focused.clearFocus();
}}
4赞 2 revs, 2 users 84%Siru malayil #119

通过创建可全局使用的扩展程序,在 Kotlin 中隐藏软键盘。为此,您需要创建一个 Singleton 类。

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

在需要隐藏键盘的 fragment 类的活动中,可以使用 mainlayout id 调用此函数,如下所示

//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()
2赞 PK Chahar #120

这对我有用

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm.isActive())
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
4赞 PINTOO AGGARWAL #121

此代码将帮助您在触摸编辑文本外部或其他任何地方时隐藏键盘。您需要在 Activity 中添加此代码,或者您可以在项目的父 Activity 中编写代码,它还会在 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);
        }
    }

0赞 4 revs, 2 users 72%BaldrSky #122

我的解决方案:

使用活动构造它(视图是可选的),使用处理程序来发布它(有一些延迟,例如,100 毫秒更好)。 直接调用输入管理器有时是行不通的。 它只有在我们可以获得 Activity 时才有效。我认为这很正常。

如果可以在调用时获取根视图组或编辑视图。只需将其发送即可获得更好的结果。

public class CloseSoftKeyboardRunnable implements Runnable
{
    Activity activity;
    View view;  // For dialog will occur context getcurrentfocus == null. send a rootview to find currentfocus.

    public CloseSoftKeyboardRunnable(Activity activity, View view)
    {
        this.activity = activity;
        this.view = view;
    }

    public CloseSoftKeyboardRunnable(Activity activity)
    {
        this.activity = activity;
    }
    @Override
    public void run() {
        if (!activity.isFinishing())
        {
            InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);

            if (view == null) {
                view = activity.getCurrentFocus();
            }
            else
            {
                try {
                    view = ((ViewGroup)view).getFocusedChild();
                }
                catch ( Exception e) {}
            }

            Window window =  activity.getWindow();

            if (window != null)
            {
                if (view == null) {
                    try {
                        view = window.getDecorView();
                        view = ((ViewGroup)view).getFocusedChild();
                    }
                    catch ( Exception e) {}
                }

                if (view == null) {
                    view = window.getDecorView();
                }

                if (view != null) {
                    if (view instanceof EditText)
                    {
                        EditText edittext = ((EditText) view);
                        edittext.setText(edittext.getText().toString()); // Reset edit text bug on some keyboards bug
                        edittext.clearFocus();
                    }

                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            }
        }
    }
}
7赞 Vin Norman #123

这些答案中有许多是不必要的复杂;这是 Kotlin 用户在类上创建一个简洁的小扩展函数的解决方案。View

创建一个基本的 Kotlin 文件(我将其命名为 我的),并介绍以下内容:KeyboardUtil.kt

fun View.hideKeyboard() {
  val imm = ContextCompat.getSystemService(context, InputMethodManager::class.java) as InputMethodManager
  imm.hideSoftInputFromWindow(windowToken, 0)
}

然后,您可以在任何视图上调用它以轻松关闭键盘。我使用 ViewBinding/DataBinding,它特别好用,例如:

fun submitForm() {
  binding.root.hideKeyboard()
  // continue now the keyboard is dismissed
}
4赞 RJnr #124

对于那些寻找喷气背包的人,请回答。

val keyboardController = LocalSoftwareKeyboardController.current

//for showing the keyboard
keyboardController?.show()
//for hiding the keyboard
keyboardController?.hide()
0赞 Akshay #125

Kotlin 版本:

fun showKeyboard(mEtSearch: EditText, context: Context) {
        mEtSearch.requestFocus()
        val imm: InputMethodManager =
            context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(mEtSearch, 0)
}
0赞 2 revs, 2 users 83%Morteza Allahyari #126

您可以使用以下扩展来隐藏和显示软键盘:

fun Fragment.showKeyboard(view: View) {
    view.isFocusableInTouchMode = true
    view.requestFocus()
    val imm = view.context?.getSystemService(Context.INPUT_METHOD_SERVICE)
        as InputMethodManager
    imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT) }

fun Fragment.hideKeyboard(view: View) {
    view.clearFocus()
    val imm = view.context?.getSystemService(Context.INPUT_METHOD_SERVICE)
       as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 0) }

要调用扩展,只需在片段中按照以下内容操作即可:

showKeyboard(Your edittext ID)

hideKeboard(Your edittext ID)
1赞 Dragan Stojanov #127

我试过这个。效果良好,在 Nougat API 24 上进行了测试。

import android.app.Activity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment


fun Activity.hideKeyboard() {
    getInsetController().hide((WindowInsetsCompat.Type.ime()))
}

fun Activity.showKeyboard() {
    getInsetController().show((WindowInsetsCompat.Type.ime()))
}

fun Fragment.hideKeyboard() {
    requireActivity().getInsetController().hide((WindowInsetsCompat.Type.ime()))
}

fun Fragment.showKeyboard() {
    requireActivity().getInsetController().show((WindowInsetsCompat.Type.ime()))
}

fun Activity.getInsetController() = WindowCompat.getInsetsController(window, window.decorView)
3赞 2 revs, 2 users 72%Jignesh Hadiya #128

要以编程方式关闭或隐藏 Android 软键盘,您可以使用以下方法:

  1. 使用 InputMethodManager:

     InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
     imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
    
  2. 使用 View 的 onEditorAction:

    如果您有 EditText 视图,并且想要在用户按下“Done”或“Enter”键时隐藏软键盘,则可以使用 onEditorAction 侦听器:

     yourEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
         @Override
         public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
             if (actionId == EditorInfo.IME_ACTION_DONE) {
                 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                 imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
                 return true;
             }
             return false;
         } });
    
  3. 以编程方式明确焦点:

    另一种方法是以编程方式清除 EditText 视图中的焦点,这将导致软键盘被隐藏:

     yourEditText.clearFocus();
    

    请记住将 yourEditText 替换为对 EditText 视图的实际引用。此外,请确保您在 Android 清单文件中声明了相应的权限,特别是 android.permission.INPUT_METHOD。

这些方法将允许您以编程方式隐藏 Android 设备上的软键盘。

评论

0赞 Peter Mortensen 10/18/2023
这可能是抄袭的结果,很可能是ChatGPT(或类似)抄袭。它与该用户的所有其他帖子完全不符。
0赞 2 revs, 2 users 65%Eeman #129

只需将 OnFocusChangeListener 添加到视图即可。例如,在本例中为 editText。

editText.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
        if (!hasFocus) {
           val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
           val focusedView = currentFocus
           if (imm != null && focusedView != null) {
              imm.hideSoftInputFromWindow(focusedView.windowToken, 0)
           }
        }
    }