문제

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