@怎麼增加一個searchView
1. 新增一個 .xml 在 res/menu下
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_search"
android:actionViewClass="android.widget.SearchView"
android:icon="@drawable/search"
android:showAsAction="always"
android:title="@string/title_txt"/>
</menu>
2. java code裡怎麼用
getMenuInflater().inflate(R.menu.XXXX, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint(getText(R.string.XXXXX));
3. 怎麼修改searchView中字反白的背景顏色(HighLight color)
在java code中set textColorHighlight
假設我要設定成 #0FC698 (雖然會超出版面,不過換行後也不好閱讀,就不換行了)
int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null); View searchPlate = searchView.findViewById(searchPlateId); if (searchPlate!=null) { int searchTextId = searchPlate.getContext().getResources().getIdentifier("android:id/search_src_text", null, null); TextView searchText = (TextView) searchPlate.findViewById(searchTextId); if (searchText!=null) { searchText.setHighlightColor(Color.parseColor("#00C698")); } }
4. 查詢字數太長,會造成 JavaBinder: !!! FAILED BINDER TRANSACTION !!!
所以需要限定查詢字數,這部份在onQueryTextChange處理
public boolean onQueryTextChange(String newText) {
//Set Query text length limit - by Francine
if(newText.length()>50){
Log.i(TAG, "Text character is more than 50");
searchView.setQuery(newText.substring(0,50), false);
}
}
ref:
techrepublic- pro-tip-customize-the-android-search-view-widget
stackoverflow- android-actionbar-customize-search-view