Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SearchView show hint text before user starts typing

I have a SearchView and trying to add a hint text. It seems you can only show the hint when the user actually taps on the SearchView, I googled a lot and tried different approaches I found on StackOverflow such as:

searchView.onActionViewExpanded();
searchView.setIconified(true);
searchView.setQueryHint("Mitarbeiter suchen");

or playing around more with the code above. I also tried adding IconifiedByDefault in XML file but it was no help.

I'm sure there's a way for it. Can anyone help, please? :)

fragment_main.xml

<android.support.v7.widget.SearchView
    android:id="@+id/search_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:queryHint="Mitarbeiter suchen">

</android.support.v7.widget.SearchView>
like image 756
Abed Naseri Avatar asked Jun 23 '17 09:06

Abed Naseri


2 Answers

Setting iconifiedByDefault and focusable properties to false worked for me.

<android.support.v7.widget.SearchView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="false"
    app:iconifiedByDefault="false"
    app:queryHint="test" />
like image 136
Gnzlt Avatar answered Oct 22 '22 09:10

Gnzlt


Checks if searchView is focused or not by isFocused() method. If matches, then it will clear focus.

searchView = (SearchView) findViewById(R.id.searchView);
searchEditText = (EditText) findViewById(R.id.search_src_text); //SearchView editText
closeButton = (ImageView) findViewById(R.id.search_close_btn); //X button of SearchView

searchView.onActionViewExpanded(); //new Added line
searchView.setIconifiedByDefault(false);
searchView.setQueryHint("Search Here");

if(!searchView.isFocused()) {
    searchView.clearFocus();
}

//Query
searchView.setOnQueryTextListener(new 
           SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {

            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            return false;
        }
    });

//This is the your x button
closeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Clear the text from EditText view
            searchEditText.setText("");

            //Clear query
            searchView.setQuery("", false);
            searchView.clearFocus();
        }
    });

Here is the screenshot of my demo app and it is in fragment.

like image 27
Shamsul Arafin Mahtab Avatar answered Oct 22 '22 11:10

Shamsul Arafin Mahtab