Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

android - How to remove focus from SearchView?

I want to remove focus and text from SearchView in onResume().

I tried searchView.clearFocus() but it is not working.

This is my xml code:

<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" />
question from:https://stackoverflow.com/questions/38411341/how-to-remove-focus-from-searchview

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I want to remove focus and text from SearchView in onResume()

To achieve this you could 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/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:focusableInTouchMode="true">

    <SearchView
        android:id="@+id/search_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:iconifiedByDefault="false"/>

</LinearLayout>

And then in your Activity:

private View rootView;
private SearchView searchView;

// ...

@Override
protected void onCreate(Bundle savedInstanceState) {

    // ...

    rootView = findViewById(R.id.root_layout);
    searchView = (SearchView) findViewById(R.id.search_view);
}

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...