SearchView query hint before clicking it

2020-08-09 08:53发布

问题:

I have a search view and I have a query hint attribute. However the hint appears only after clicking on the search view. Is there a way to make it appear before it has been clicked?

<SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView4"
        android:layout_marginBottom="14dp"
        android:layout_marginTop="30dp"
        android:queryHint="Search" />

I have seen another SO question with a similar query, but it wasn't solved. That's why I am asking again.

回答1:

You can add these below lines:

SearchView searchView = (SearchView) findViewById(R.id.searchView);
searchView.onActionViewExpanded();
searchView.setIconified(true);

and add this to hiding focus (Keyboard)

 new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                search.clearFocus();
            }
    }, 300);


回答2:

Use this XML:

android:queryHint="hint"
app:queryHint="hint"
app:defaultQueryHint="hint"
android:iconifiedByDefault="false"  // this line
app:iconifiedByDefault="false"

app used for {android.support.v7.widget.SearchView}



回答3:

You can just add android:iconifiedByDefault="false" it just displays the query hint string by default



回答4:

make setIconified(false)-that works for me that works,but when it is unclicked,again hint disappears



回答5:

This worked for me:

searchView.onActionViewExpanded();
new Handler().postDelayed(new Runnable() 
{
    @Override
    public void run() {
          searchView.clearFocus();
    }
}, 300);

Also, don't forget to add these to manifest.xml:

<intent-filter>
    <action android:name="android.intent.action.SEARCH"/>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>


回答6:

This is a complete XML, You can try this.

<androidx.appcompat.widget.SearchView
                        android:id="@+id/searchview"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:iconifiedByDefault="false"
                        app:iconifiedByDefault="false"
                        app:queryHint="@string/search"
                        app:searchIcon="@drawable/ic_action_search"/>


回答7:

Try this:

SearchView searchView = new SearchView(getSherlockActivity().getSupportActionBar().getThemedContext());
  searchView.setQueryHint("Search for countries…");
  searchView.setIconified(false);

  menu.add("Search")
      .setIcon(R.drawable.abs__ic_search)
      .setActionView(searchView)
      .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);


回答8:

In xml, You can use this android:queryHint="Search"