0

My Android project deals with various Fragments and multiple classes. There is one fragment class which holds the Sliding Menu Back and rightsliding menu option. When a EditText field is pressed then the softkeyboard is shown and when the menu or another action bar buttons are pressed the softkeyboard should close but it doesn't

The function for hidekeyboard is one class while the EditText fields are in multiple classes.

How should i go about this.

Saraschandraa
  • 478
  • 1
  • 9
  • 27

2 Answers2

0

Try this :

// To hide Keyboard if touched outside its area.. //

@Override
public boolean dispatchTouchEvent(MotionEvent event) {

    View v = getCurrentFocus();
    boolean ret = super.dispatchTouchEvent(event);

    if (v instanceof EditText) {
        View w = getCurrentFocus();
        int scrcoords[] = new int[2];
        w.getLocationOnScreen(scrcoords);
        float x = event.getRawX() + w.getLeft() - scrcoords[0];
        float y = event.getRawY() + w.getTop() - scrcoords[1];

        Log.d("Activity",
                "Touch event " + event.getRawX() + "," + event.getRawY()
                        + " " + x + "," + y + " rect " + w.getLeft() + ","
                        + w.getTop() + "," + w.getRight() + ","
                        + w.getBottom() + " coords " + scrcoords[0] + ","
                        + 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 this helps.

Siddharth_Vyas
  • 9,487
  • 10
  • 36
  • 67
0

Add this in manifest file android:windowSoftInputMode="stateAlwaysHidden" , So initially your screen won't pop up with keyboard.

Call this method to enable it.

  private void softKeyboard() {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(partialEditText, InputMethodManager.SHOW_IMPLICIT);
        }

Invoke this method when you are about to move to other screen

        private void hideKeyboard() {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(partialEditText.getWindowToken(), 0);
        }
Kalai.G
  • 1,602
  • 13
  • 21