Changing options menu icon in actionbar depending on an open Fragment

允我心安 提交于 2019-12-05 01:28:47

Use this to get a reference to the menu item:

    menu.findItem(resourceId).setIcon(drawableId);

You have to put the code to change the icon in onCreateOptionsMenu().

Please refer to my example below:

    public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    getMenuInflater().inflate(R.menu.option_menu, menu);

    if (needToChangeMenuItem){

        menu.findItem(resourceId).setIcon(drawableId);
    }

    manageMenuIcon(menu);

    needToChangeMenuItem = false;


    return true;
}


    public void manageMenuIcon(Menu menu){
    if (bluetoothIconOn){
        menu.findItem(R.id.secure_connect_scan).setIcon(R.drawable.bluetoothon);
    } else
        menu.findItem(R.id.secure_connect_scan).setIcon(R.drawable.bluetoothoff);

    if (gpsIconOn)
        menu.findItem(R.id.gps).setIcon(R.drawable.gps);
    else
        menu.findItem(R.id.gps).setVisible(false);

    if (slipAndDropIconOn)
        menu.findItem(R.id.fall).setIcon(R.drawable.fall);
    else
        menu.findItem(R.id.fall).setVisible(false);

    if (fesConnectIconOn)
        menu.findItem(R.id.fesConnection).setIcon(R.drawable.fesconnect);
    else
        menu.findItem(R.id.fesConnection).setVisible(false);


}


    public void changeMenuItem(int resId, int draId){


    needToChangeMenuItem = true;
    resourceId = resId;
    drawableId = draId;

    invalidateOptionsMenu();        


}
MenuItem mi = (MenuItem) view.findViewById(R.id.opt_mnu_action);
mi.setIcon(R.drawable.ico_1);

In your Fragment's onCreateOptionsMenu, load this menu, and keep a reference to the menu item (it is not part of the fragment's view hierarchy so you can't use findViewById).

Whenerver you are ready to update the icon, use mi.setIcon(R.drawable.ico_1); and call invalidateOptionsMenu().

UPDATED:

return super.onCreateOptionsMenu(menu);

This will actually return false, since the base implementation doesn't do that. Instead skip it, or just call super.onCreateOptionsMenu(menu); first, do your stuff and then return true.

First add actionOverFlowButtonStyle into your main theme

<style name="AppTheme" parent="AppBaseTheme">

    <item name="android:actionOverflowButtonStyle">@style/MyActionButtonOverflow</item>
</style>

Define the New style for action over flow button

<style name="MyActionButtonOverflow" parent="android:style/Widget.Holo.Light.ActionButton.Overflow">
    <item name="android:src">@drawable/ic_menu</item>
</style>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!