简体   繁体   中英

How Can I set Action bar button icon by Java code

I have set the action bar button using xml, but I want to set the icon using java code because I want the icon to be changeable.

I want to set the icon in onCreateOptionsMenu() .

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.mymenu, menu);
    return true;
}

you first get the item using Menu.findItem() , then call MenuItem.setIcon() to set the icon

code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.mymenu, menu);
    menu.findItem(R.id.messages).setIcon(R.drawable.ic_action_email);
    return true;
}

Get your menu item by index and set icon:

menu.getItem(index).setIcon(R.drawable.icon);

for ex:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.mymenu, menu);
    menu.getItem(index).setIcon(R.drawable.icon);
    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM