Search code examples
androidkeyboardandroid-edittextandroid-scrollview

Hide keyboard in Scrollview when user touches (outside), scrolls or clicks (other views) in Android


This might look like a redundant and already answered query but I am stuck. I have browsed through previously shared plethora of responses but none of them turned out to be a holistic solution.

Here's how the main activity xml looks like:

<RelativeLayout >

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

    <ScrollView >

        <LinearLayout >

            <android.support.v7.widget.CardView >

                <LinearLayout >

                </LinearLayout>

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView >

            </android.support.v7.widget.CardView>

        </LinearLayout>

    </ScrollView>

</RelativeLayout>

<android.support.design.widget.NavigationView />

The Problem

There is a edit text view in child linear layout of first card view. As of now, if I click on it, the keyboard pops up but doesn't hide when I click elsewhere or scroll the page or click any other view (there's a drop down).

What I plan to do is to hide the keyboard when, 1. I click anywhere outside the edit text view. 2. Scroll the page. 3. Interact with other views (the drop down).

Possible Solutions Tried

how to dismiss keyboard from editText when placed in scroll view - This one isn't working at all for me.

How to hide soft keyboard on android after clicking outside EditText? - There was one solution from @vida which worked partially, as in when clicked outside, the keyboard did dismiss. But then again, that's only a partial solution to what I am trying to achieve.

I would appreciate if someone could share a solution (or procedure) to sort this one out. Thanks!


Solution

  • You could try to override the Scroll Views onClickListener to call this method every time the user clicks anywhere on the app. If that doesnt work just set the outer relative layout to be clickable and everytime the layout is clicked you can call this hideKeyboard method!

    public void hideKeyboard(View view) {
       InputMethodManager im =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
       im.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }