How to change all ToolBar's icons color dynamically without styling toolbar

前端 未结 2 871
北海茫月
北海茫月 2021-01-03 02:24

I have been looking a way to change the color of all elements in a toolbar working like an ActionBar dynamically.

Specifications:

2条回答
  •  一向
    一向 (楼主)
    2021-01-03 02:45

    I was facing same problem here. What I did for ToolBar's elements:

    1. For background color: toolbar.setBackgroundColor(Color.parseColor("#xxxxxxxx"));
    2. For text color: toolbar.setTitleTextColor(Color.parseColor("#xxxxxxxx"));
    3. For hamburger/drawer button:

      int color = Color.parseColor("#xxxxxxxx");
      final PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP);
      
      for (int i = 0; i < toolbar.getChildCount(); i++){
      
          final View v = toolbar.getChildAt(i);
      
          if(v instanceof ImageButton) {
              ((ImageButton)v).setColorFilter(colorFilter);
          }
      }
      
    4. For ActionMenuItemView (toolbar's buttons including overflow button):

      private void colorizeToolBarItem(AppCompatActivity activity, final PorterDuffColorFilter colorFilter, final String description) {
      
          final ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
          final ViewTreeObserver viewTreeObserver = decorView.getViewTreeObserver();
      
          viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
              @Override
              public void onGlobalLayout() {
      
                  final ArrayList outViews = new ArrayList<>();
                  decorView.findViewsWithText(outViews, description,
                      View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
                  if (outViews.isEmpty())
                      return;
      
                  ActionMenuItemView overflow = (ActionMenuItemView)outViews.get(0);
                  overflow.getCompoundDrawables()[0].setColorFilter(colorFilter);
                  removeOnGlobalLayoutListener(decorView,this);
              }
          });
      }
      
    5. For overflow menu's items text: take a look at this link

提交回复
热议问题