Close/hide the Android Soft Keyboard

2018-12-30 22:41发布

I have an EditText and a Button in my layout.

After writing in the edit field and clicking on the Button, I want to hide the virtual keyboard. I assume that this is a simple piece of code, but where can I find an example of it?

30条回答
与风俱净
2楼-- · 2018-12-30 23:29

I have spent more than two days working through all of the solutions posted in the thread and have found them lacking in one way or another. My exact requirement is to have a button that will with 100% reliability show or hide the on screen keyboard. When the keyboard is in its hidden state is should not re-appear, no matter what input fields the user clicks on. When it is in its visible state the keyboard should not disappear no matter what buttons the user clicks. This needs to work on Android 2.2+ all the way up to the latest devices.

You can see a working implementation of this in my app clean RPN.

After testing many of the suggested answers on a number of different phones (including froyo and gingerbread devices) it became apparent that android apps can reliably:

  1. Temporarily hide the keyboard. It will re-appear again when a user focuses a new text field.
  2. Show the keyboard when an activity starts and set a flag on the activity indicating that they keyboard should always be visible. This flag can only be set when an activity is initialising.
  3. Mark an activity to never show or allow the use of the keyboard. This flag can only be set when an activity is initialising.

For me, temporarily hiding the keyboard is not enough. On some devices it will re-appear as soon as a new text field is focused. As my app uses multiple text fields on one page, focusing a new text field will cause the hidden keyboard to pop back up again.

Unfortunately item 2 and 3 on the list only work reliability when an activity is being started. Once the activity has become visible you cannot permanently hide or show the keyboard. The trick is to actually restart your activity when the user presses the keyboard toggle button. In my app when the user presses on the toggle keyboard button, the following code runs:

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

This causes the current activity to have its state saved into a Bundle, and then the activity is started, passing through an boolean which indicates if the keyboard should be shown or hidden.

Inside the onCreate method the following code is run:

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

If the soft keyboard should be shown, then the InputMethodManager is told to show the keyboard and the window is instructed to make the soft input always visible. If the soft keyboard should be hidden then the WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM is set.

This approach works reliably on all devices I have tested on - from a 4 year old HTC phone running android 2.2 up to a nexus 7 running 4.2.2. The only disadvantage with this approach is you need to be careful with handling the back button. As my app essentially only has one screen (its a calculator) I can override onBackPressed() and return to the devices home screen.

查看更多
弹指情弦暗扣
3楼-- · 2018-12-30 23:31

Please try this below code in onCreate()

EditText edtView=(EditText)findViewById(R.id.editTextConvertValue);
edtView.setInputType(0);
查看更多
永恒的永恒
4楼-- · 2018-12-30 23:31

To help clarify this madness, I'd like to begin by apologizing on behalf of all Android users for Google's downright ridiculous treatment of the soft keyboard. The reason there are so many answers, each different, for the same simple question because this API, like many others in Android, is horribly designed. I can think of no polite way to state it.

I want to hide the keyboard. I expect to provide Android with the following statement: Keyboard.hide(). The end. Thank you very much. But Android has a problem. You must use the InputMethodManager to hide the keyboard. OK, fine, this is Android's API to the keyboard. BUT! You are required to have a Context in order to get access to the IMM. Now we have a problem. I may want to hide the keyboard from a static or utility class that has no use or need for any Context. or And FAR worse, the IMM requires that you specify what View (or even worse, what Window) you want to hide the keyboard FROM.

This is what makes hiding the keyboard so challenging. Dear Google: When I'm looking up the recipe for a cake, there is no RecipeProvider on Earth that would refuse to provide me with the recipe unless I first answer WHO the cake will be eaten by AND where it will be eaten!!

This sad story ends with the ugly truth: to hide the Android keyboard, you will be required to provide 2 forms of identification: a Context and either a View or a Window.

I have created a static utility method which can do the job VERY solidly, provided you call it from an 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);
}

Be aware that this utility method ONLY works when called from an Activity! The above method calls getCurrentFocus of the target Activity to fetch the proper window token.

But suppose you want to hide the keyboard from an EditText hosted in a DialogFragment? You can't use the method above for that:

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

This won't work because you'll be passing a reference to the Fragment's host Activity, which will have no focused control while the Fragment is shown! Wow! So, for hiding the keyboard from fragments, I resort to the lower-level, more common, and uglier:

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

Below is some additional information gleaned from more time wasted chasing this solution:

About windowSoftInputMode

There's yet another point of contention to be aware of. By default, Android will automatically assign initial focus to the first EditText or focusable control in your Activity. It naturally follows that the InputMethod (typically the soft keyboard) will respond to the focus event by showing itself. The windowSoftInputMode attribute in AndroidManifest.xml, when set to stateAlwaysHidden, instructs the keyboard to ignore this automatically-assigned initial focus.

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

Almost unbelievably, it appears to do nothing to prevent the keyboard from opening when you touch the control (unless focusable="false" and/or focusableInTouchMode="false" are assigned to the control). Apparently, the windowSoftInputMode setting applies only to automatic focus events, not to focus events triggered by touch events.

Therefore, stateAlwaysHidden is VERY poorly named indeed. It should perhaps be called ignoreInitialFocus instead.

Hope this helps.


UPDATE: More ways to get a window token

If there is no focused view (e.g. can happen if you just changed fragments), there are other views that will supply a useful window token.

These are alternatives for the above code if (view == null) view = new View(activity); These don't refer explicitly to your activity.

Inside a fragment class:

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

Given a fragment fragment as a parameter:

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

Starting from your content body:

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

UPDATE 2: Clear focus to avoid showing keyboard again if you open the app from the background

Add this line to the end of the method:

view.clearFocus();

查看更多
千与千寻千般痛.
5楼-- · 2018-12-30 23:32

Thanks to this SO answer, I derived the following which, in my case, works nicely when scrolling through the the fragments of a ViewPager...

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

private void showKeyboard() {   
    // Check if no view has focus:
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }
}
查看更多
十年一品温如言
6楼-- · 2018-12-30 23:32

In some cases this methods can works except of all others. This saves my day :)

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);
        }
    }
}
查看更多
何处买醉
7楼-- · 2018-12-30 23:34

For my case, I was using the a SearchView in the actionbar. After a user performs a search, the keyboard would pop open again.

Using the InputMethodManager did not close the keyboard. I had to clearFocus and set the focusable of the search view to false:

mSearchView.clearFocus();
mSearchView.setFocusable(false);
查看更多
登录 后发表回答