Reputation: 38940
Is there a way to hide the virtual keyboard once I click a button in android? The keyboard originally pops up when the user touches an edittext component; I'd like it to close once a button is pushed.
Upvotes: 4
Views: 16938
Reputation: 1706
Use Below Code
your_button_id.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
// TODO: handle exception
}
}
});
Upvotes: 2
Reputation: 2066
Best Practice for hiding keyboard:
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
It will automatically receive the current focus and will hide keyboard. Doesn't matter how many EditText
views you have.
Upvotes: 17