MenuItem tinting on AppCompat Toolbar

前端 未结 8 1962
轮回少年
轮回少年 2020-11-28 19:26

When I use drawables from the AppCompat library for my Toolbar menu items the tinting works as expected. Like this:



        
8条回答
  •  一向
    一向 (楼主)
    2020-11-28 20:03

    Setting a ColorFilter (tint) on a MenuItem is simple. Here is an example:

    Drawable drawable = menuItem.getIcon();
    if (drawable != null) {
        // If we don't mutate the drawable, then all drawable's with this id will have a color
        // filter applied to it.
        drawable.mutate();
        drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
        drawable.setAlpha(alpha);
    }
    

    The above code is very helpful if you want to support different themes and you don't want to have extra copies just for the color or transparency.

    Click here for a helper class to set a ColorFilter on all the drawables in a menu, including the overflow icon.

    In onCreateOptionsMenu(Menu menu) just call MenuColorizer.colorMenu(this, menu, color); after inflating your menu and voila; your icons are tinted.

提交回复
热议问题