简体   繁体   中英

Hiding Android Keyboard after Pressing Back Button

I am using this code to hide the keyboard:

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

This works well. However, I noticed a bug. If I have initially hidden the keyboard using my phone physical back button, then I called the above method, the keyboard will be shown instead of hidden. In other word, seem like the Android system failed to detect I have hidden the keyboard using back button. Instead of hiding the keyboard, it show the keyboard. How to solve this?

just change this line from

 imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

to

 imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

As using toggle change the state on the basis of current state. If its hidden it will show and vice versa.

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

//show-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

It's because you are toggling the keyboard. Try this:

InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

In your Activity

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

or you can add in Androidmanifest.xml

<activity
    android:name=".views.activities.tile_details.TileDetailActivity"
    android:screenOrientation="portrait"
    android:theme="@style/TileDetails.AppTheme.Light"
    android:windowSoftInputMode="stateHidden" />

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM