Reputation: 14314
I have a menu item as part of my action bar menu, and I am setting the action view class to the search widget like so:
<item android:id="@+id/menu_search"
android:title="Search"
android:icon="@drawable/ic_menu_search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView" />
This makes the search widget pop out when it is clicked - however, I want it to always be visible, and I also want to be able to set the query hint etc.
When I attempt to call SearchView searchItem = (SearchView) menu.findItem(R.id.menu_search)
to get a reference to it, it throws an error as the item cannot be cast to a SearchView
.
Upvotes: 17
Views: 20141
Reputation: 1539
I added these lines of code and it worked.
searchView.setHint(getString(R.string.places));
searchView.setHintTextColor(R.color.black);
Sample code
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_item,menu);
MenuItem item = menu.findItem(R.id.action_search);
MaterialSearchView searchView = findViewById(R.id.searchview);
searchView.setMenuItem(item);
searchView.setHint(getString(R.string.places));
searchView.setHintTextColor(R.color.black);
return true;
}
Material Search View library github link
Upvotes: 0
Reputation: 434
minimum API level should be 11 then The error will not be shown
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
Upvotes: 0
Reputation: 3828
You can set hint text to searchview using the api setQueryHint (CharSequence hint)
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setQueryHint("Query Hint");
Upvotes: 86
Reputation: 172
This will make the ActionView search box always show, by default:
searchView.setIconifiedByDefault(false);
This tells the search box to always be expanded. Iconified means that you need to tap the icon to make the search box appear.
Upvotes: 12
Reputation: 2910
Try getActionView; findItem is returning a MenuItem, not the View it uses
(SearchView)menu.findItem(R.id.menu_search).getActionView()
Upvotes: 2