Reputation: 4419
How can I change a menu action item background color in a toolbar?
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:edo="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/my_action"
android:icon="@mipmap/icon"
android:title="@string/title"
app:showAsAction="always" />
</menu>
Then in my activity:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_actions, menu);
final MenuItem item = menu.findItem(R.id.my_action);
MenuItemCompat.getActionView(item).setBackgroundColor(ContextCompat.getColor(this, R.color.red));
return super.onCreateOptionsMenu(menu);
}
This is not working, because getActionView always returns null.
Upvotes: 0
Views: 1010
Reputation: 1575
getActionView() is working when there's a custom actionView from setActionView() in my case.
Create a layout and set it as action view to your menu item like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.new_menu, menu);
MenuItem item = menu.findItem(R.id.my_action);
View myView = LayoutInflater.from(this).inflate(R.layout.menu_item_layout, null);
((ImageView) myView.findViewById(R.id.btnEdit)).setOnClickListener(this);
item = MenuItemCompat.setActionView(item, myView);
MenuItemCompat.getActionView(item).setBackgroundColor(ContextCompat.getColor(this, R.color.blue));
return true;
}
menu_item_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/btnEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/red"
android:minHeight="0dp"
android:minWidth="0dp"
android:src="@drawable/img_edt" />
Like this you can set color either in getActionView(item).setBackgroundColor(..) or in menu_item_layout.xml file itself.
Upvotes: 0
Reputation: 16010
Here we go:
public void changeActionMenuItemsBackground(int color) {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
for (int i = 0; i < toolbar.getChildCount(); i++) {
final View v = toolbar.getChildAt(i);
if (v instanceof ActionMenuView) {
v.setBackgroundColor(color);
}
}
}
You can call it right in onCreateOptionsMenu()
or later
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
changeActionMenuItemsBackground(Color.BLACK);
return true;
}
I hope, it helps
Upvotes: 1