I have an app using to scan barcode, so I want to hide the soft keyboard. My app worked fine on devices with android 7, 9... but when I installed it on device run android 11, the keyboard display when I scan.
I searched and tried many ways, like this in Manifest:
android:windowSoftInputMode="stateHidden"
Or this in activity:
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
None of these works. Does anyone have different solutions, please help. Thank you.
CodePudding user response:
Here is two different methods for activity and fragment, Hope it might work for you.
// Method : Hide Keyboard
@JvmStatic
fun hideKeyboard(activity: Activity) {
val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
var view = activity.currentFocus
if (view == null) {
view = View(activity)
}
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
@JvmStatic
fun hideKeyboardInFragment(context: Context?, view: View?/*Your EditText*/) {
if (context != null && view != null) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
CodePudding user response:
this is worked for me, please check
public static void hideKeyboard(Context context) {
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
// check if no view has focus:
View v = ((Activity) context).getCurrentFocus();
if (v == null)
return;
inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}