user1556566
user1556566

Reputation:

How to Hide virtual keyboard when clicking out side in Android

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?

Upvotes: 0

Views: 1801

Answers (3)

Ram kiran Pachigolla
Ram kiran Pachigolla

Reputation: 21191

@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

Upvotes: 5

mukesh
mukesh

Reputation: 4140

Declare in your manifest

<activity android:name=".YourActivity"
 android:windowSoftInputMode="stateHidden"/>

Upvotes: 0

Rushabh Patel
Rushabh Patel

Reputation: 3080

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.

Upvotes: 0

Related Questions