Pradeep Deshmukh Pradeep Deshmukh - 4 months ago 19
Android Question

How to remove focus from search view?

I want to remove focus and text from

SearchView
in
onResume()
I tried
searchView.clearFocus();
but it is not working.

<SearchView
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/toolbar"
android:layout_alignTop="@+id/toolbar"
android:layout_centerVertical="true"
android:layout_marginBottom="4dp"
android:layout_marginTop="4dp"
android:iconifiedByDefault="false"
android:paddingLeft="16dp"
android:paddingRight="16dp" />


this is my xml code.

Answer

You could just set your root layout focusable with the android:focusableInTouchMode attribute and request focus on that View in onResume().

For example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:focusableInTouchMode="true">

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginTop="4dp"
        android:iconifiedByDefault="false"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"/>

</LinearLayout>

And then in your Activity:

View root;
SearchView searchView;

// ...

@Override
protected void onCreate(Bundle savedInstanceState) {

    // ...

    root = findViewById(R.id.rootLayout);
    searchView = (SearchView) findViewById(R.id.searchView);
}

@Override
protected void onResume() {
    super.onResume();

    searchView.setQuery("", false);
    root.requestFocus();
}