Reputation: 1236
I hope you can give me a hand on this one.
I have an Action bar item with a default icon set.(android:icon="@drawable/ic_action_volume_on") but the thing is that i need to change it somehow programmatically at my method "onOptionsItemSelected" and since I recently started with Android I'm a bit lost...
Upvotes: 0
Views: 111
Reputation:
You can do this simply by defining
private Menu menu;
and in onCreateOptionMenu callback assign value to menu and get menu inflater like this
@Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu=menu;
getMenuInflater().inflate(R.menu.menu_bar, menu);
return true;
}
And finally you can write this line to change icon in your preferred method
menu.findItem(R.id.item_id).setIcon(R.drawable.your_icon);
Upvotes: 1
Reputation: 1557
First you have to save a menu instance on the onCreateOptionsMenu
:
private Menu menu;
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
this.menu = menu
...
}
Then, you can create the following method:
private void setItemView(int itemId, int layoutId) {
if (menu != null) {
final Menuitem myItem = menu.findItem(itemId);
if (myItem != null) {
MenuItemCompat.setActionView(myItem, layoutId);
}
}
}
It replaces the current icon of your item by a view. For example if you want to display a ProgressBar
you can create this layout (let's name it item_custom_view.xml
):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="56dp"
android:layout_height="wrap_content"
android:minWidth="56dp" >
<ProgressBar
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_gravity="center" />
</FrameLayout>
Finally, in your Activity
, just call the setItemView
method. Put in parameters the id of your item and the id of your layout (in this case R.layout.item_custom_view
).
Upvotes: 2