12

I have an EditText in my Activity. As soon as the Activity starts I force the soft keyboard to open using.

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

Now if the soft keypad is open and I press the home button, it remains open. How can I force it close on home press?

stealthjong
  • 10,858
  • 13
  • 45
  • 84
Vibhuti
  • 702
  • 1
  • 7
  • 21

2 Answers2

22
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(Your Button.getWindowToken(), 0);
Priyanka
  • 677
  • 5
  • 20
Rishi
  • 987
  • 6
  • 16
1
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    View view = getCurrentFocus();
    boolean ret = super.dispatchTouchEvent(event);

    if (view 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;
}

This code closes the keyboard when you touch anywhere on the screen.

stealthjong
  • 10,858
  • 13
  • 45
  • 84
Rashmi.B
  • 1,787
  • 2
  • 18
  • 34
  • @ rashmi The solution that you have suggested is to close the soft keyboard when it is called implicitly.here I am forcing it to open when my activity opens imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); So,This solution doesnt work – Vibhuti Jan 12 '12 at 07:21