Remove the focus of an EditText by pressing outside of it on Android

0

I have several EditText and other components, try that when you press out of EditText you lose the focus and the keyboard is hidden.

layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

        <EditText
            android:id="@+id/textview_1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:imeOptions="flagNoExtractUi"
            android:inputType="textUri"
            android:singleLine="true"
            tools:text="Dummy text" />

        <EditText
            android:id="@+id/textview_2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:imeOptions="flagNoExtractUi"
            android:inputType="textUri"
            android:singleLine="true"
            tools:text="Dummy text 2" />

        <Switch
            android:id="@+id/switch_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

</LinearLayout>

The focus is always on the last EditText , for example if you click on the switch it operates correctly, but keeping the focus on EditText, so that the keyboard if it is visible is annoying on the screen.

    
asked by Webserveis 18.07.2018 в 20:54
source

1 answer

2

Searching for SO I found the solution:

The technique is to intercept the touch on the screen to check that the focus had a TextView and remove it

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Log.i(TAG, "dispatchTouchEvent: ");
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        View view = getCurrentFocus();
        if (view != null && view instanceof EditText) {
            Rect r = new Rect();
            view.getGlobalVisibleRect(r);
            int rawX = (int)ev.getRawX();
            int rawY = (int)ev.getRawY();
            if (!r.contains(rawX, rawY)) {
                view.clearFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }
    return super.dispatchTouchEvent(ev);
}

To have an effect, you must add to the layout father android:focusableInTouchMode="true" in my case use DrawerLayout I had to put it in CoordinatorLayout of app_bar.xml

    
answered by 18.07.2018 / 20:54
source