Show soft keyboard for EditText when Fragment starts

At times When app screen starts, we may need to show Soft keyboard Popup for the EditText, which having focus. So user don’t need to touch on the EditText to show keyboard.

show soft keyboard

To show keyboard for EditText view when Activity starts. We can just implement in XML design file in EditText tag by using <requestFocus />. see below


But the above XML code not works when using in Fragment, to show keyboard when Fragment screen starts.

Solution to show soft keyboard

We need to handle in code to force show keyboard. Following code works fine..

* TODO showInputMethod
public void showInputMethod() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);


And You can hide the Softkeyboard, when user touched on any other place than the EditText in Activity screen, using following code (place this code in Activity)

  /* (non-Javadoc)
* @see
  public boolean dispatchTouchEvent(MotionEvent event) {
      View v = getCurrentFocus();
      boolean ret = super.dispatchTouchEvent(event);
      if (this instanceof SkylineMessagesActivityAdv) {
          return false;
      if (v instanceof EditText) {
          View w = getCurrentFocus();
          int scrCoords[] = new int[2];
          float x = event.getRawX() + w.getLeft() - scrCoords[0];
          float y = event.getRawY() + w.getTop() - scrCoords[1];
          if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom())) {
              InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
              imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
      return ret;

Hope it helps somebody..

Cheers 🙂

You may be also interested in



  1. Abhilash Srivastava | | Reply

    thank you for this…

  2. Andrej | | Reply

    Thanks mate, this was just what I was looking for.

  3. HiM | | Reply

    It works fine but how to close this .. I have tried all the solution . In my scenario I start a fragment and show the keyboard and press the home button .. my app goes in background but keyboard still there on tab/phone screen .. it seems weird cause when app is closed or in background why keyboard is not closing or hiding , I was trying to write some code on pause of fragment but did not help.

    • Praveen B | | Reply

      Hi Him,
      I edited above post and given code to hide softkeyboard. Please try it. It may work for you.

Leave a Reply

Your email address will not be published. Required fields are marked *