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 when touching outside the keyboard. Can someone provide a simple example of how to achieve this?
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 when touching outside the keyboard. Can someone provide a simple example of how to achieve this?
For the kotlin users out there here is a kotlin extension method that has worked for my use cases:
fun View.hideKeyboard() {
val imm = this.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
put it in a file called ViewExtensions (or what have you) and call it on your views just like a normal method.
First, you should add from the XML file add android:imeOptions field and change its value to actionUnspecified|actionGo as below
<android.support.design.widget.TextInputEditText
android:id="@+id/edit_text_id"
android:layout_width="fill_parent"
android:layout_height="@dimen/edit_text_height"
android:imeOptions="actionUnspecified|actionGo"
/>
Then In the java class add a setOnEditorActionListener and add InputMethodManager as below
enterOrderNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
return true;
}
return false;
}
});
This was work for me. It is in Kotlin for hiding the keyboard.
private fun hideKeyboard() {
val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val focusedView = activity?.currentFocus
if (focusedView != null) {
inputManager.hideSoftInputFromWindow(focusedView.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS)
}
}
class KeyboardUtils{
companion object{
fun hideKeyboard(activity: Activity) {
val imm: InputMethodManager = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
var view: View? = activity.currentFocus
if (view == null) {
view = View(activity)
}
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
}
Then just call it wherever you need
KeyboardUtils.hideKeyboard(requireActivity())
KeyboardUtils.hideKeyboard(this)
Hide Keyboard from an Activity
fun hideKeyboard() {
val view = this.currentFocus
if (view != null) {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
Hide Keyboard from a Fragment
fun hideKeyboard() {
val imm = requireActivity().getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
val view = requireActivity().currentFocus
if (view != null) {
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
Hide Keyboard After User Interaction
button.setOnClickListener {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(currentFocus?.windowToken, 0)
}
Hide Keyboard Without a View Reference
fun hideKeyboard() {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
}
Hide Keyboard When Navigating Between Fragments or Activities
override fun onPause() {
super.onPause()
hideKeyboard() // Call the hide keyboard function here
}
Hide Keyboard Using an Extension Function
fun Activity.hideKeyboard() {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
val view = this.currentFocus ?: View(this)
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
surround it with try catch, so that is keyboard is already closed, app would not crash :
try{
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}catch (Exception e)
{
e.printStackTrace();
}
After reading all the answers above and in another post, I still didn't succeed in getting the keyboard to open automatically.
In my project I created a dialog (AlertDialog) dynamically (by programming it without or with minimum of needed XML).
So I was doing something like:
dialogBuilder = new AlertDialog.Builder(activity);
if(dialogBuilder==null)
return false; //error
inflater = activity.getLayoutInflater();
dialogView = inflater.inflate(layout, null);
...
And after finishing setting-up all the views (TextView, ImageView, EditText,etc..) I did:
alertDialog = dialogBuilder.create();
alertDialog.show();
After playing around with all the answers I found out that most of them work IF you know WHERE to put the request... And that was the key to all.
So, the trick is to put it BEFORE the creation of the dialog: alertDialog.show() in my case, this worked like charm:
alertDialog = dialogBuilder.create();
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//And only when everything is finished - let's bring up the window -
alertDialog.show();
//Viola... keyboard is waiting for you open and ready...
//Just don't forget to request focus for the needed view (i.e. EditText..)
I'm quite sure this principle is the same with all windows, so pay attention to the location of your "showKeyboard" code - it should be before the window is launched.
A small request from the Android SDK dev team:
I think that all this is unnecessary as you can see thousands of programmers from all over the world are dealing with this ridiculous and trivial problem, while its solution should be clean and simple:
IMHO if I get requestFocus() to an input-oriented view (such as EditText), the keyboard should open automatically, unless the user asks not-to, so, I think the requestFocus() method is the key here and should accept boolean showSoftKeyboard with default value of true: View.requestFocus(boolean showSoftKeyboard);
Hope this will help others like me.
Kotlin version
val imm: InputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
Activity seems like a decent approach fun Activity.closeKeyboard() { (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).apply { hideSoftInputFromWindow(window.decorView.windowToken, 0) } }I'm using following Kotlin Activity extensions:
/**
* Hides soft keyboard if is open.
*/
fun Activity.hideKeyboard() {
currentFocus?.windowToken?.let {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager?)
?.hideSoftInputFromWindow(it, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
/**
* Shows soft keyboard and request focus to given view.
*/
fun Activity.showKeyboard(view: View) {
view.requestFocus()
currentFocus?.windowToken?.let {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager?)
?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
To show keyboard on application start:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
view.requestFocus();
new Handler().postDelayed(new Runnable() {
public void run() {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
}, 1000);
Hi This is simple if you are working with Kotlin i belive you can easily convert the code to Java too first in your activity use this function when your activity is load for example in the onCreate() call it.
fun hideKeybord (){
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (inputManager.isAcceptingText){
inputManager.hideSoftInputFromWindow(currentFocus.windowToken, 0)
}
}
as i mentiond call this Function in your onCreate() methode then add this android:windowSoftInputMode="stateAlwaysHidden" line to your activity in manafest.xml file Like this...
<activity
android:name=".Activity.MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar"
android:windowSoftInputMode="stateAlwaysHidden">
This code snippet can helped:
final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
if (inputMethodManager != null && inputMethodManager.isActive()) {
if (getCurrentFocus() != null) {
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
It can be called in different methods according to need (ex. onPause, onResume, onRestart ...)
//In Activity
View v = this.getCurrentFocus();
if (v != null) {
InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
//In Fragment
View v = getActivity().getCurrentFocus();
if (v != null) {
InputMethodManager im = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
```
Here is the easiest way to hide the soft keyboard with Kotlin:
//hides soft keyboard anything else is tapped( screen, menu bar, buttons, etc. )
override fun dispatchTouchEvent( ev: MotionEvent? ): Boolean {
if ( currentFocus != null ) {
val imm = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
imm.hideSoftInputFromWindow( currentFocus!!.windowToken, 0 )
}
return super.dispatchTouchEvent( ev )
}
Don't forget: In system settings of smartphone is in "Input methods and Languages -> Physical keyboard -> Show OnScreen Keyboard -> On/Off". This settings "interfere" all programming solutions which are here! I had to disable/enable this settings too for complete hide/show onscreen keyboard! Because I am developing for device MC2200 I did it with "EMDK Profile manage -> Ui manager -> Virtual Keyboard state -> Show/Hide"
I tried this. Works well, tested on Nougat API 24.
import android.app.Activity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
fun Activity.hideKeyboard() {
getInsetController().hide((WindowInsetsCompat.Type.ime()))
}
fun Activity.showKeyboard() {
getInsetController().show((WindowInsetsCompat.Type.ime()))
}
fun Fragment.hideKeyboard() {
requireActivity().getInsetController().hide((WindowInsetsCompat.Type.ime()))
}
fun Fragment.showKeyboard() {
requireActivity().getInsetController().show((WindowInsetsCompat.Type.ime()))
}
fun Activity.getInsetController() = WindowCompat.getInsetsController(window, window.decorView)
Try this:
Force fully the Android soft input keyboard:
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
This works in a fragment with Android 10 (API 29):
val activityView = activity?.window?.decorView?.rootView
activityView?.let {
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(it.windowToken, 0)
}
You can hide the keyboard in Kotlin as well using this code snippet.
fun hideKeyboard(activity: Activity?) {
val inputManager: InputMethodManager? =
activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as?
InputMethodManager
// Check if no view has focus:
val v = activity?.currentFocus ?: return
inputManager?.hideSoftInputFromWindow(v.windowToken, 0)
}
There is a new API in Android 11 called WindowInsetsController. Apps can get access to a controller from any view, by which we can use the hide() and show() methods:
val controller = view.windowInsetsController
// Show the keyboard (IME)
controller.show(Type.ime())
// Hide the keyboard
controller.hide(Type.ime())
I have tried all of solutions very much but no solution work for me, so I found my solution: You should have boolean variables like:
public static isKeyboardShowing = false;
InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
And in a touch screen event you call:
@Override
public boolean onTouchEvent(MotionEvent event) {
if(keyboardShowing==true){
inputMethodManager.toggleSoftInput(InputMethodManager.RESULT_UNCHANGED_HIDDEN, 0);
keyboardShowing = false;
}
return super.onTouchEvent(event);
}
And in EditText is in anywhere:
yourEditText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
yourClass.keyboardShowing = true;
}
});
Try this in Kotlin
private fun hideKeyboard(){
val imm = activity!!.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(activity!!.currentFocus!!.windowToken, 0)
}
Try this in Java
private void hideKeyboard(){
InputMethodManager imm =(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}