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?

有帮助吗?

解决方案

@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

其他提示

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.

Declare in your manifest

<activity android:name=".YourActivity"
 android:windowSoftInputMode="stateHidden"/>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top