如何设置可见性Android软键盘

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

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


#1楼

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

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

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

对于旧版本,我得到了很好的效果(但远非完美)与OnGlobalLayoutListener ,添加了的援助ViewTreeObserver从我的根视图,然后检查是否是这个样子的键盘:

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

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

最后一个解决方案可能是瞬间显示键盘,并且使选择手柄混乱。

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

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

更新:刚刚找到了用于从不显示键盘的对话框,并且可以在所有版本中使用:

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

#2楼

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

#3楼

这是您在Android版Mono(AKA MonoDroid)中的操作方法

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

#4楼

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

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

这将迫使键盘在所有情况下都处于隐藏状态。 在某些情况下,您将需要传入InputMethodManager.HIDE_IMPLICIT_ONLY作为第二个参数,以确保仅在用户未明确强制键盘出现时(通过按住菜单)才隐藏键盘。

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

Kotlin语法

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

#5楼

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

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

#6楼

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

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

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

#7楼

到目前为止, 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 loader, Object data) {
    /* parameters not valid ... */

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

    /* parameters valid ... */
}


#8楼

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

您可以在我的应用程序干净RPN中看到此功能的有效实现。

在许多不同的手机(包括froyo和姜饼设备)上测试了许多建议的答案后,很明显,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 2.2的4年旧HTC手机到运行4.2.2的nexus 7。 这种方法的唯一缺点是您需要小心处理后退按钮。 由于我的应用程序基本上只有一个屏幕(它有一个计算器),因此我可以覆盖onBackPressed()并返回到设备主屏幕。


#9楼

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

#10楼

为了澄清这种疯狂,我首先代表所有Android用户道歉,表示谷歌对软键盘的彻底荒谬对待。 对于同一个简单问题,答案如此之多,原因各不相同,因为该API与Android中的许多其他API一样,都是经过可怕设计的。 我认为没有礼貌的说法。

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

这就是隐藏键盘如此具有挑战性的原因。 亲爱的Google:当我在寻找蛋糕的食谱时,地球上没有RecipeProvider会拒绝向我提供食谱,除非我先回答RecipeProvider蛋糕吃完并在哪里食用!

这个可悲的故事以一个丑陋的事实结尾:要隐藏Android键盘,您将需要提供两种形式的标识: 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);
}

请注意,只有从Activity调用时,此实用程序方法才有效! 上面的方法调用目标Activity getCurrentFocus来获取正确的窗口令牌。

但是,假设您想从DialogFragment托管的EditText隐藏键盘? 您不能为此使用以上方法:

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

这是行不通的,因为你会被传递一个参考Fragment的主机Activity ,这将有没有集中控制,同时该Fragment显示! 哇! 因此,为了隐藏键盘的片段,我求助于较低级别的,更常见的且更难看的:

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

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

关于windowSoftInputMode

还有另一点需要注意。 默认情况下,Android会自动将初始焦点分配给Activity的第一个EditText或可焦点控件。 当然,InputMethod(通常是软键盘)将通过显示自身来响应焦点事件。 设置为stateAlwaysHidden时, AndroidManifest.xmlwindowSoftInputMode属性指示键盘忽略此自动分配的初始焦点。


几乎令人难以置信的是,它似乎无济于事,无法阻止您在触摸控件时打开键盘(除非为控件分配了focusable="false"和/或focusableInTouchMode="false" )。 显然,windowSoftInputMode设置仅适用于自动聚焦事件,不适用于由触摸事件触发的聚焦事件。

因此, stateAlwaysHidden的确确实得很差。 也许应该将其称为ignoreInitialFocus

希望这可以帮助。


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

如果没有焦点视图(例如,如果您只是更改片段,可能会发生),那么其他视图将提供有用的窗口标记。

if (view == null) view = new View(activity);这些是上述代码的替代方法if (view == null) view = new View(activity); 这些没有明确提及您的活动。

在片段类内部:

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

给定一个fragment fragment作为参数:

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

从内容主体开始:

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

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

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

view.clearFocus();


#11楼

用这个

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

#12楼

请在onCreate()尝试以下代码

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

#13楼

除了上述解决方案之外 ,如果您想不参考用于打开键盘的(EditText)字段的情况下从任何位置关闭软键盘,但是如果该字段已聚焦,则仍要这样做,则可以使用这(来自一个活动):

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

#14楼

这应该工作:

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

#15楼

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

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

#16楼

对于隐藏软键盘也有用的是:

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

这可以用来抑制软键盘,直到用户实际触摸editText视图为止。


#17楼

Meier的解决方案也对我有用。 在我的情况下,我的应用程序的顶层是tabHost,我想在切换选项卡时隐藏关键字-我从tabHost视图获取窗口令牌。

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

#18楼

只需在您的活动中使用以下优化代码即可:

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

#19楼

简短的答案

在您的OnClick侦听onEditorAction中,使用IME_ACTION_DONE调用EditTextIME_ACTION_DONE

button.setOnClickListener(new OnClickListener() {

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

下钻

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


检查此相关答案


#20楼

我的情况是,我的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 );
}

#21楼

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

#22楼

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

#23楼

由于有了这个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);
    }
}

#24楼

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

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

#25楼

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



#26楼

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

#27楼

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

#28楼

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

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

我将“后退按钮”用引号引起来,因为以上内容不会触发所onBackPressed()活动的onBackPressed() 。 它只是关闭键盘。

请确保暂停一会儿再继续,因为关闭后退按钮需要一点时间,因此,直到短暂的暂停后(1秒足够长的时间, )。


#29楼

如果此处所有其他答案都无法满足您的要求,则可以使用另一种手动控制键盘的方法。

创建一个函数,该函数将管理EditText的某些属性:

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

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

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

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

现在,每当您要手动打开键盘时,请调用:

setEditTextFocus(true);

对于结束通话:

setEditTextFocus(false);

#30楼

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

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

#31楼

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

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

这里通过HIDE_IMPLICIT_ONLY在的位置showFlag0在的位置hiddenFlag 。 它将强制关闭软键盘。

你可能感兴趣的:(如何设置可见性Android软键盘)