timeshift117
timeshift117

Reputation: 1800

SearchView gains focus and opens keyboard when returning from another activity

When I return from another activity to the main activity, the searchView gains focus and the keyboard opens, I managed to stop the keyboard from opening by using:

    getWindow().setSoftInputMode(
              WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

but this is not sufficient, if the actionbar drop down menu is opened and closed the keyboard reappears, because the searchView still has focus (remember I only closed the keyboard). I have tried to get a reference to the searchView and make it lose focus, but this has not worked.

So basically, I just want the searchView to never have focus or prompt the keyboard to open, unless the searchView text area is actually touched.

Upvotes: 13

Views: 8202

Answers (4)

Syed Hasan
Syed Hasan

Reputation: 311

this works for me in onResume();

searchview.clearFocus();

Upvotes: 0

Leveraging on Adam S' answer, if you don't have any earlier View in the hierarchy before the SearchView, you could always include a dummy View like so:

<View
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:focusableInTouchMode="true"/>

<android.support.v7.widget.SearchView
    android:iconifiedByDefault="false"
    ... />

This also worked for me!

Upvotes: 7

while initializing

mSearchView.setIconifiedByDefault(false);

And when came back, put this in onResume() or onCreateOptionsMenu(if search is in menu)

mSearchView.setIconified(false);

Then keyboard won't open when you come back until you click on edit text of searchview

Upvotes: 1

Adam S
Adam S

Reputation: 16394

This is due to the SearchView being the first focusable view when the activity is brought back into view - the same issue can be seen for EditTexts.

The solution is the same - set an earlier view in the hierarchy to focusable. In my case, this was the Toolbar my SearchView was on top of:

<android.support.v7.widget.Toolbar
    style="@style/ToolbarStyle"
    android:focusableInTouchMode="true"
    android:id="@+id/search_activity_toolbar"
    android:layout_height="?attr/actionBarSize"
    android:layout_width="match_parent"/>

<android.support.v7.widget.SearchView
    android:iconifiedByDefault="false"
    ... />

Now I can gain focus on my SearchView when entering the activity (clearFocus(); requestFocus(...);), then when you exit the activity via a search result, then return by pressing Back, the keyboard is in the same state as when you left.

Note that some of the other solutions on the linked question, namely setting windowSoftInputMode="stateUnchanged" on the Activity did not work for me.

Upvotes: 22

Related Questions