Android Studio 2.3, Android 4.3, Galaxy Nexus.
I want the selected button (when clicked) to hide soft keyboard.
Questions:
- What is the name of this button?
- How to handle a click of this button in a fragment?
You can handle the back button being pressed by using the following method:
// When not using fragments
@Override
public void onBackPressed() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
The code inside the onBackPressed method was found here; Close/hide the Android Soft Keyboard
// When using a fragment
fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener()
{
@Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
return false;
}
} );
You can use the onKeyPreIme
method to handle click of the button.
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
return true;
}