如何自定义android中工具栏上的搜索图标?
问题描述:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:appcompat="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/action_search"
android:icon="@drawable/search"
appcompat:actionViewClass="android.support.v7.widget.SearchView"
appcompat:showAsAction="ifRoom"
android:title="Search"/>
</menu>
我想改变search image在右上角,目前它是黑色的,我想将它变为橙色如何自定义android中工具栏上的搜索图标?
答
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_notifications, menu);
this.menu = menu;
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_clear_all) {
showToast("Clear All");
return true;
}
return super.onOptionsItemSelected(item);
}
下创建资源的XML文件>菜单。
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".YourActivityName" >
<item
android:id="@+id/action_clear_all"
android:title="@string/noti_clear_all"
android:icon="@drawable/ic_clear_all"
android:orderInCategory="100"
app:showAsAction="ifRoom" />
</menu>
答
您可以通过setColorFilter
重置MenuItem的颜色。
Drawable可以更改为任何颜色。
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_menu_frag, menu);
// replace MenuItem with your own
MenuItem item = menu.getItem(0);
final Drawable drawable = item.getIcon();
if (drawable != null) {
final int color = Color.RED;
drawable.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN));
}
}
答
在onCreateOptionsMenu(Menu menu, MenuInflater inflater)
您可以使用此:
注意:您可能希望使用PorterDuff.Mode.SRC_IN
代替PorterDuff.Mode.MULTIPLY
)
MenuItem searchItem = menu.findItem(R.id.action_search);
int color = 0; // SPECIFY THE COLOUR YOU WANT HERE. I suggest you retrieve colour from colors.xml
menuItem.getIcon().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
但我个人很可能只是手动更改绘制的颜色(即用彩色替换drawable)。
答
使用下面的XML在你的菜单项
<item
android:id="@+id/menu_search"
android:actionViewClass="android.widget.SearchView"
android:icon="@drawable/search"
android:showAsAction="ifRoom|collapseActionView"
android:title="@string/menu_search" />
//请确保您在活动或片段使用相同的菜单项的XML。
参考http://*.com/questions/10445760/how-to-change-the-default-icon-on-the-searchview-to-be-use-in-the-action-bar-on – sasikumar
目前它是黑色的。这是一个图像有黑色。您必须创建一个颜色为橙色的图像。并取代它! –
已经尝试过,但不能正常工作 –