我的布局中有一个EditText和一个Button。

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


您可以使用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中执行此操作,请使用:上下文getSystemService(Context.INPUT_METHOD_SERVICE)作为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)
}

请在onCreate()中尝试以下代码

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

隐藏软键盘也很有用:

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

这可用于抑制软键盘,直到用户实际触摸editText View。

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

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

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

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

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

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

在继续之前,请确保暂停一段时间,因为关闭后退按钮需要一段时间。因此,在短暂暂停后(1秒足够长),才能注册随后的视图等单击。

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

创建一个用于管理EditText的某些财产的函数:

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

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

然后,确保在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);

在如此的搜索中,我找到了一个适合我的答案

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

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

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

这里在showFlag位置传递HIDE_IMPLICIT_ONLY,在hiddenFlag位置传0。它将强制关闭软键盘。

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

在v3.2.4_r1中,添加了setSoftInputShownOnFocus(布尔显示)来控制天气或在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 XML声明中使用TextView#setImeOptions(int)或:

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

更新:刚刚发现对话框用于从不显示键盘,并且在所有版本中都有效:

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

下面是如何在Mono for Android(AKA MonoDroid)中实现的

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

您还可以研究在EditText上使用setImeOption。

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

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

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

有时你只需要按回车键来折叠键盘在“编辑文本”框中指定属性

 android:imeOptions="actionDone" 

这将将Enter按钮更改为Done按钮,该按钮将关闭键盘。

我创建了一个布局,部分来自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);
    }   
}

在我的案例中,我使用的是操作栏中的SearchView。用户执行搜索后,键盘将再次弹出。

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

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

到目前为止,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 ... */
}

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

你可以在我的应用程序clean RPN中看到这一点的有效实现。

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

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

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

不幸的是,列表中的第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()并返回设备主屏幕。

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

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

然后我突然发现了一个明显获胜的组合:

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

结合你平时的食谱

blahblaj.hideSoftInputFromWindow ...

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

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

我想隐藏键盘。我希望为Android提供以下语句:Keyboard.hide().结束。非常感谢你。但Android有一个问题。必须使用InputMethodManager隐藏键盘。好吧,这是Android的键盘API。但是!您需要有上下文才能访问IMM。现在我们有一个问题。我可能想将键盘隐藏在一个静态类或实用程序类中,该类不使用或不需要任何上下文。或者更糟糕的是,IMM要求您指定要隐藏键盘的视图(甚至更糟糕的,窗口)。

这就是隐藏键盘如此具有挑战性的原因。亲爱的谷歌:当我在查找蛋糕的食谱时,世界上没有食谱提供商会拒绝向我提供食谱,除非我首先回答世界卫生组织会吃蛋糕以及在哪里吃蛋糕!!

这个悲伤的故事以丑陋的事实结尾:要隐藏Android键盘,你需要提供两种形式的标识:上下文和视图或窗口。

我已经创建了一个静态实用程序方法,只要您从“活动”调用它,它就可以非常可靠地完成任务。

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以获取适当的窗口标记。

但是,假设您想对DialogFragment中托管的EditText隐藏键盘?您不能使用上述方法:

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

这不会起作用,因为您将传递一个对Fragment的主机Activity的引用,在显示Fragment时,该主机Activity将没有焦点控制!哇!因此,为了隐藏键盘的碎片,我选择了更低级、更常见、更丑陋的方法:

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

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

关于windowSoftInputMode

还有一个争论点需要注意。默认情况下,Android会自动将初始焦点分配给“活动”中的第一个EditText或可聚焦控件。很自然,InputMethod(通常是软键盘)将通过显示自己来响应焦点事件。AndroidManifest.xml中的windowSoftInputMode属性设置为stateAlwaysHidden时,指示键盘忽略自动分配的初始焦点。

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

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

因此,stateAlwaysHidden的名称确实非常糟糕。它可能应该被称为ignoreInitialFocus。


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

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

如果(view==null)view=new view(activity),则这些是上述代码的替代方案;这些并没有明确提到你的活动。

在片段类中:

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

给定片段片段作为参数:

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

从内容主体开始:

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

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

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

view.clearFocus();

使用这个

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

作为这一全面解决方案的替代方案,如果您想从任何地方关闭软键盘,而没有对用于打开键盘的(EditText)字段的引用,但仍然希望在该字段被聚焦时进行此操作,则可以使用(从“活动”):

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

这应该是有效的:

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

这种方法总是不惜任何代价。只要在你想隐藏键盘的地方使用它

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

这对我有用:

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

这对我有用。。

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

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

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

这对我有用。

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

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

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

使用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提供了大量的代码!

简短的回答

在OnClick监听器中,使用IME_ACTION_DONE调用EditText的onEditorAction

button.setOnClickListener(new OnClickListener() {

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

向下钻取

我觉得这种方法更好,更简单,更符合Android的设计模式。在上面的简单示例中(通常在大多数常见情况下),您将拥有一个具有焦点的EditText,并且它通常也是首先调用键盘的一个(在许多常见情况下它肯定能够调用它)。以同样的方式,它应该是释放键盘的人,通常这可以通过ImeAction来完成。只要看看带有android:imeOptions=“actionDone”的EditText的行为,您就可以通过相同的方式实现相同的行为。


检查此相关答案

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

记下所有这些答案,简单地说,我写了一个常用的方法:

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

我有一个例子,我的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 );
}

试试这个

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

对于开放式键盘:

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

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

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;

        }
    });

我几乎尝试了所有这些答案,我遇到了一些随机问题,特别是三星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);
}
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);
    }
}

多亏了这个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);
    }
}

有时,您可能有一个活动包含包含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);

在AndroidManifest.xml中的<activity..>set android:windowSoftInputMode=“stateAlwaysHidden”

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

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

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

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

添加到Manifest文件中的活动android:windowSoftInputMode=“stateHidden”。例子:

<activity
            android:name=".ui.activity.MainActivity"
            android:label="@string/mainactivity"
            android:windowSoftInputMode="stateHidden"/>
/** 
 *
 *   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);
}

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

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

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

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

或者,如果您希望始终隐藏键盘,请在AndroidManifest中使用此选项:

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

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

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

 android:windowSoftInputMode="stateAlwaysHidden|adjustPan"

它会起作用的。

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

每次都像魔术般

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

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

在我的项目中,我动态地创建了一个对话框(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();

在玩转了所有答案后,我发现如果你知道把请求放在哪里,大多数答案都有效。。。这是一切的关键。

所以,诀窍是在创建对话框之前使用它: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开发团队的一个小请求:

我认为所有这些都是不必要的,因为你可以看到来自世界各地的数千名程序员正在处理这个荒谬而琐碎的问题,而其解决方案应该是干净而简单的:IMHO如果我将requestFocus()获取到面向输入的视图(如EditText),键盘应该自动打开,除非用户要求不打开,因此,我认为requestFocus方法是这里的关键,应该接受默认值为true的布尔showSoftKeyboard:view.requestFocus(布尔showSoftKeyboard);

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

试试这个

简单,您可以在活动中调用


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

在您的主活动中调用


 hideKeyboardwithoutPopulate(MainActivity.this);

这是工作。。

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

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

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

您可以简单地将此代码添加到要隐藏软键盘的位置“

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

以下是最佳解决方案

解决方案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);

or

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

如果有人感兴趣的话,我已经为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为空。我增加了使用反射来检测键盘是否关闭的额外关闭方式

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

在Android中,要通过InputMethodManage隐藏Vkeyboard,您可以通过传递包含焦点视图的窗口的标记来隐藏SoftInputFromWindow。

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

如果您的应用程序以API Level 21或更高为目标,则可以使用默认方法:

editTextObj.setShowSoftInputOnFocus(false);

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

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

一些科特林代码:

从“活动”中隐藏键盘:

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

非常简单的方法

我在所有的项目中都这样做,并且像做梦一样工作。在声明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>

可以为任何视图创建Extension函数

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

与活动一起使用的示例

window.decorView.hideKeyboard();

与视图一起使用的示例

etUsername.hideKeyboard();

快乐编码。。。

事实上,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();
    }
}

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

我正在使用以下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)
    }
}

当您想手动隐藏键盘时,单击按钮:

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

当您想在屏幕上除编辑文本以外的任何地方隐藏键盘时在活动中重写此方法:

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

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

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

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

下面是隐藏和显示方法。

科特林

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

在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);
}
 fun hideKeyboard(appCompatActivity: AppCompatActivity) {
        val view = appCompatActivity.currentFocus
        val imm = appCompatActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }
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);
}

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

调用此方法以隐藏软键盘

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

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

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

将其放在名为ViewExtensions的文件中(或其他文件),并像普通方法一样在视图中调用它。

如果你使用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()

嗨,这很简单,如果您使用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”行添加到manafist.xml文件中的活动中。。。

<activity
    android:name=".Activity.MainActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar"
    android:windowSoftInputMode="stateAlwaysHidden">
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

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

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)

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

只需在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);
}

此代码段可以帮助:

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

首先,您应该从XML文件中添加addandroid: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(新的TextView.OnEditorActionlister(){

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

这是我的工作。这是在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)
        }
    }

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

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

一个简单的解决方法是只编辑Text.setEnabled(false);editText.setEnabled(true);在Button onClick()方法中。

试试这个强制完全android软输入键盘

在Helper类中创建方法。

InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm != null)
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

我使用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)
}

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

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

android:imeOptions="actionDone" 

对于科特林爱好者。我创建了两个扩展函数。为了隐藏键盘的乐趣,您可以将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)
    }
}

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

android:focusable="false"

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

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

}

通过将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)

        }

您也可以使用此代码段在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)
 }

从碎片移动到碎片时

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

•通过扩展功能的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)
}

•使用

现在,在您的Activity或Fragment中,hideKeyboard()可以清晰地访问,也可以从EditText的实例调用它,例如:

editText.hideKeyboard()

科特林

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)

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

val controller = view.windowInsetsController

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

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

Android 11中有一个名为WindowInsetsController的新API,应用程序可以从任何视图访问控制器,通过它我们可以使用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

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

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

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

如果你在.xml android中设置:focused=“true”,那么他就不会工作,因为这是一个不可更改的设置。

因此解决方案:android:focusedByDefault=“true”

比他设置一次,可以隐藏/显示键盘

碎片形式的科特林溶液:

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"

有很多答案,如果一切都不起作用,那么,这里有一个提示:),您可以制作EditText,

edittext.setAlpha(0f);

由于alpha方法,将看不到该编辑文本,现在使用上面的答案了解如何使用EditText显示/隐藏软键盘。

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

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

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

这里的视图是您当前的视图,

以下是使用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 )
}

现在,将近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())

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

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

首先将依赖实现“androidx.core:core-ktx:1.7.0”添加到appgradle

然后从ViewCompat或WindowCompat类获取InsetsController。

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

已编辑添加对Dialog的支持。在BottomSheetDialog中提供@隆德夫。使用更安全的方式获取活动,而不是直接从上下文中强制转换。

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

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

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

在需要隐藏键盘的片段类的活动中,可以使用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()

这对我很有用

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm.isActive())
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 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);
        }
    }

我的解决方案:

用活动构造它(视图是可选的),使用处理程序发布它(有一些延迟,例如100ms更好)。直接调用输入管理器有时不起作用。只有在工作时才能获得“活动”。我认为这很正常。

如果您可以在通话时获取根视图组或编辑视图,只需发送它即可获得更好的结果。

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

这些答案中有很多是不必要的复杂;这是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
}

对于那些寻找喷气背包的人来说,写下答案。

val keyboardController = LocalSoftwareKeyboardController.current

//for showing the keyboard
keyboardController?.show()
//for hiding the keyboard
keyboardController?.hide()

Kotlin版本:

fun showKeyboard(mEtSearch: EditText, context: Context) {
        mEtSearch.requestFocus()
        val imm: InputMethodManager =
            context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(mEtSearch, 0)
}

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

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)