Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hide default keyboard on click in android

Tags:

android

i want to hide the soft keyboard when i click out side of editbox in a screen. how can i do this?

like image 205
Sujit Avatar asked Oct 23 '10 19:10

Sujit


1 Answers

Had to edit this one to get it to work. Added a check to see if the focused view is a EditText.

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

Could probably be done in a smoother way but it works really well.

like image 171
Daniel Avatar answered Sep 21 '22 08:09

Daniel