Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android:Hide keyboard after button click

I need to hide the android keyboard after a button click.

I have seen many examples of how to do this, however, they all appear to use a specific editText object.

e.g.

InputMethodManager imm = (InputMethodManager)getSystemService(       Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0); 

My problem is that I am building the screen dynamically, thus there could be mane edit text fields. Is there a way the keyboard can be hidden without me having to specify which editText object I am hiding it for.

like image 289
Martin Shinks Avatar asked Nov 27 '12 21:11

Martin Shinks


People also ask

How do I hide my keyboard from clicking?

To hide keyboard, use the following code. InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); inputMethodManager. hideSoftInputFromWindow(v. getApplicationWindowToken(),0);

How can I hide my keyboard while typing?

Tap the back button on your Android. It's the left-pointing arrow button at the bottom of the screen, either at the bottom-left or bottom-right corner. The keyboard is now hidden. The back button may be a physical button or on the touch screen.

How do I hide the soft keyboard on Android after clicking outside EditText?

and put the following code in the onTouch method. InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm. hideSoftInputFromWindow(getCurrentFocus(). getWindowToken(), 0);


2 Answers

You could instead set it to your layout, ie:

LinearLayout mainLayout;  // Get your layout set up, this is just an example mainLayout = (LinearLayout)findViewById(R.id.myLinearLayout);  // Then just use the following: InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mainLayout.getWindowToken(), 0); 

This is an example assuming that your layout will be created regardless of how many EditText objects (or other objects) are placed on it.

Edit: Also, something I find very useful is to make sure that the keyboard is hidden when an activity first launches (ie: if an EditText is the first thing focused). To do that, I put this in onCreate() method of Activity:

 this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
like image 166
burmat Avatar answered Oct 14 '22 15:10

burmat


Dont forget to use try catch blog because in case when your keyboard not open and if you use key key board hide code app will crash

try {     InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);     imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } catch (Exception e) {     // TODO: handle exception } 
like image 41
Prashant Maheshwari Andro Avatar answered Oct 14 '22 16:10

Prashant Maheshwari Andro