سؤال

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