0

I am following this tutorial.

The code is working fine for one editText. But now I have many (nearly 10) EditText fields. If I repeat this code for every field, the code will be lengthy. Can anybody let me know how to disable a virtual keyboard when click outside of any field?

Community
  • 1
  • 1
  • It's native, you dont need to do nothing to get this behaviour. The keyboard just show yourself when focused in a EditText, but when you leave it, the keyboard become invisible. Just make sure which none edit text are focused. – lucasjmatias Oct 04 '12 at 12:35
  • The answer on question which you used as tutorial contains exact answer on your question. getFields() method return not single EditText field but all fields from activity – amukhachov Oct 04 '12 at 12:38

3 Answers3

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

May be this will help you.. check it

Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78
0
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

Simply use this code to hide the keyboard inside the onTouchDown() method of an OnTouchListener that is tied to the parent layout.

Hope this will help for you.

Rushabh Patel
  • 3,052
  • 4
  • 26
  • 58
0

Declare in your manifest

<activity android:name=".YourActivity"
 android:windowSoftInputMode="stateHidden"/>
mukesh
  • 4,140
  • 5
  • 29
  • 40
  • check by, replace 'stateHidden' by 'adjustResize' or 'adjustPan' – mukesh Oct 04 '12 at 13:07
  • I have tried all of [these](http://developer.android.com/reference/android/R.attr.html#windowSoftInputMode) but no use –  Oct 04 '12 at 13:09