MenuItem tinting on AppCompat Toolbar

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

    Most of the solutions in this thread either use a newer API, or use reflection, or use intensive view lookup to get to the inflated MenuItem.

    However, there's a more elegant approach to do that. You need a custom Toolbar, as your "apply custom tint" use case does not play well with public styling/theming API.

    public class MyToolbar extends Toolbar {
        ... some constructors, extracting mAccentColor from AttrSet, etc
    
        @Override
        public void inflateMenu(@MenuRes int resId) {
            super.inflateMenu(resId);
            Menu menu = getMenu();
            for (int i = 0; i < menu.size(); i++) {
                MenuItem item = menu.getItem(i);
                Drawable icon = item.getIcon();
                if (icon != null) {
                    item.setIcon(applyTint(icon));
                }
            }
        }
        void applyTint(Drawable icon){
            icon.setColorFilter(
               new PorterDuffColorFilter(mAccentColor, PorterDuff.Mode.SRC_IN)
            );
        }
    
    }
    

    Just make sure you call in your Activity/Fragment code:

    toolbar.inflateMenu(R.menu.some_menu);
    toolbar.setOnMenuItemClickListener(someListener);
    

    No reflection, no view lookup, and not so much code, huh?

    And now you can ignore the ridiculous onCreateOptionsMenu/onOptionsItemSelected.

提交回复
热议问题