Question

I am new to Android development. My requirement is that I want to hide the android virtual keypad when I click on the outside of an EditText widget. Please help.

Was it helpful?

Solution

To hide the virtual keyboard you can execute the following code:

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

Simply put that code inside the onTouchDown() method of an OnTouchListener that is tied to the parent layout.

OTHER TIPS

Just check this.

@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];

    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;
}

Override this method where you have edit text in your activity..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top