MenuItem tinting on AppCompat Toolbar

前端 未结 8 1976
轮回少年
轮回少年 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:23

    Here is the solution that I use; you can call it after onPrepareOptionsMenu() or the equivalent place. The reason for mutate() is if you happen to use the icons in more than one location; without the mutate, they will all take on the same tint.

    public class MenuTintUtils {
        public static void tintAllIcons(Menu menu, final int color) {
            for (int i = 0; i < menu.size(); ++i) {
                final MenuItem item = menu.getItem(i);
                tintMenuItemIcon(color, item);
                tintShareIconIfPresent(color, item);
            }
        }
    
        private static void tintMenuItemIcon(int color, MenuItem item) {
            final Drawable drawable = item.getIcon();
            if (drawable != null) {
                final Drawable wrapped = DrawableCompat.wrap(drawable);
                drawable.mutate();
                DrawableCompat.setTint(wrapped, color);
                item.setIcon(drawable);
            }
        }
    
        private static void tintShareIconIfPresent(int color, MenuItem item) {
            if (item.getActionView() != null) {
                final View actionView = item.getActionView();
                final View expandActivitiesButton = actionView.findViewById(R.id.expand_activities_button);
                if (expandActivitiesButton != null) {
                    final ImageView image = (ImageView) expandActivitiesButton.findViewById(R.id.image);
                    if (image != null) {
                        final Drawable drawable = image.getDrawable();
                        final Drawable wrapped = DrawableCompat.wrap(drawable);
                        drawable.mutate();
                        DrawableCompat.setTint(wrapped, color);
                        image.setImageDrawable(drawable);
                    }
                }
            }
        }
    }
    

    This won't take care of the overflow, but for that, you can do this:

    Layout:

    
    

    Styles:

    
    

    This works as of appcompat v23.1.0.

提交回复
热议问题