如何修改SearchView的样式
public SearchView createSearchView(Context context) {
SearchView searchView = new SearchView(context);
EditText editText = ((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text));
if (editText != null) {
editText.setTextColor(Color.WHITE);
editText.setHint(R.string.pleaseEnterNickname);
editText.setHintTextColor(Color.WHITE);
}
ImageView searchCloseIcon = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
if (searchCloseIcon != null) {
searchCloseIcon.setImageResource(R.mipmap.icon_close);
}
ImageView voiceIcon = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_voice_btn);
if (voiceIcon != null) {
voiceIcon.setImageResource(R.mipmap.icon_voice_white);
}
return searchView;
}
以下几种方法都不可以自定义搜索按钮图片
ImageView searchIcon = (ImageView) searchView.findViewById(R.id.search_mag_icon);
if (searchIcon != null) {
searchIcon.setImageResource(R.mipmap.icon_search);
}
ImageView searchIcon = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_mag_icon);
if (searchIcon != null) {
searchIcon.setImageResource(R.mipmap.icon_search);
}
int searchIconId = searchView.getContext().getResources().getIdentifier("android:id/search_button", null, null);
ImageView searchIcon = (ImageView) searchView.findViewById(searchIconId);
if (searchIcon != null) {
searchIcon.setImageResource(R.mipmap.icon_search);
}
最后通过修改showAsAction
属性,将其设置为collapseActionView
,成功设置自定义图片标
<item xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/menu_search"
android:actionViewClass="android.support.v7.widget.SearchView"
android:icon="@mipmap/icon_search"
android:showAsAction="ifRoom|collapseActionView"
android:title="@string/menuSearch"
app:icon="@mipmap/icon_search"
app:searchIcon="@mipmap/icon_search"
app:showAsAction="ifRoom|collapseActionView"
tools:ignore="AppCompatResource" />