5

Android Studio 2.3, Android 4.3, Galaxy Nexus.

Screenshot: enter image description here

I want the selected button (when clicked) to hide soft keyboard.

Questions:

  1. What is the name of this button?
  2. How to handle a click of this button in a fragment?
Michael
  • 3,093
  • 7
  • 39
  • 83
Alexei
  • 14,350
  • 37
  • 121
  • 240

2 Answers2

0

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;
    }
} );
Community
  • 1
  • 1
Michael
  • 3,093
  • 7
  • 39
  • 83
  • I need to handle back button in Fragment. Fragment not has method "onBackPressed" – Alexei May 16 '17 at 17:45
  • Okay i will look into solutions for that. In the mean time accept my edit so other users can see that a fragment is being used – Michael May 16 '17 at 17:53
  • When keyboard is show and I click back button the method "onKey(...)" not call. – Alexei May 17 '17 at 07:23
0

You can use the onKeyPreIme method to handle click of the button.

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) { 
    return true;
}
Shaishav Jogani
  • 2,111
  • 3
  • 23
  • 33
Haris ali
  • 773
  • 1
  • 13
  • 19