user273084
user273084

Reputation: 151

Best way to unfocus edittext when user interacts with another (non-texual) input element

I have an activity with some edittexts and some checkboxes, etc.

I have validators set on text entries that get executed when a text entry loses focus. But the problem is when the user clicks/touches a checkbox, edittext doesn't lose focus and therefore the validator is not run.

What is the best way for causing unfocus of text entries when the user touches another input field? I know I can e.g. set a handler on every checkbox to force unfocusing of text fields happen, but I think there is probably a more concise/general method for this purpose; Setting a handler on every checkbox seems too cumbersome and error prone.

thank u.

Upvotes: 1

Views: 431

Answers (1)

Gioan Le
Gioan Le

Reputation: 1168

You can try this way(it only is an example).

your_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sv_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusableInTouchMode="true"
        android:orientation="vertical">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="EditText 1" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="EditText 2" />

        ..............other views................

    </LinearLayout>

</ScrollView>

Using android:focusableInTouchMode="true" in the LinearLayout to make the EditText is focused when touching on it( or when starting this activity there is not auto focus to any EditText also).

In your activity:

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.test);

        ScrollView svContent = findViewById(R.id.sv_content);
        svContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                int action  = motionEvent.getAction();

                if(action == MotionEvent.ACTION_MOVE || action == MotionEvent.ACTION_UP) {
                    View focusView = getCurrentFocus();
                    if (focusView != null) {
                        // The code for unfocus here

                        return true;
                    }
                }
                return false;
            }
        });
    }

Upvotes: 1

Related Questions