i want to hide keyboard in fragments in android.Because once it displays it remain visible in all fragments.I try this method
public static void hideKeyboard(Context ctx) {
InputMethodManager inputManager = (InputMethodManager) ctx
.getSystemService(Context.INPUT_METHOD_SERVICE);
// check if no view has focus:
View v = ((Activity) ctx).getCurrentFocus();
if (v == null)
return;
inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
and call this method on button click
signIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideKeyboard(ctx);
login();
}
});
but this give error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference"
Hiding the Soft Keyboard Programmatically You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your edit field. This will force the keyboard to be hidden in all situations.
Setting android:isScrollContainer = "false" inside the ScrollView worked for me. According to the documentation, settings "isScrollContainer" to true means that the scroll view can be resized to shrink its overall window so that there is space for an input method.
To hide keyboard, use the following code. InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); inputMethodManager. hideSoftInputFromWindow(v. getApplicationWindowToken(),0);
For Java
try this one
public static void hideSoftKeyboard(Activity activity) {
if (activity.getCurrentFocus() == null) {
return;
}
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
to call this just pass below code from your onclick of button
signIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideSoftKeyboard(getActivity());
login();
}
});
For Kotlin
fun hideSoftKeyboard(activity:Activity) {
if (activity.getCurrentFocus() == null){
return
}
val inputMethodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0)
}
pass below code from your onclick of button
signIn.setOnClickListener(object:View.OnClickListener() {
fun onClick(v:View) {
hideSoftKeyboard(getActivity())
login()
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With