开发者

Setting hint text for search widget when used as part of menu

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 开发者_如何学JAVAto it, it throws an error as the item cannot be cast to a SearchView.


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");

Refer the documentation


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.


Try getActionView; findItem is returning a MenuItem, not the View it uses

(SearchView)menu.findItem(R.id.menu_search).getActionView()


minimum API level should be 11 then The error will not be shown

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="18" />


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜