2015-09-14 3 views
3

Я искал способ изменить цвет все элементы в панели инструментов, работающие как ActionBar динамически.Как изменить все значки значков ToolBar динамически без панели инструментов моделирования.

Технические характеристики:

  • Использование parent="Theme.AppCompat.Light.NoActionBar" на styles.xml
  • AppCompat v7 22
  • установка setSupportActionBar() в моем AppCompatActivity
  • я получил цвета из запроса POST (обычно # FF-- ---- формат)

Я прочитал следующее сообщение:

  1. How do I change the color of the ActionBar hamburger icon?
  2. How to change color of hamburger icon in material design navigation drawer
  3. Can't change navigation drawer icon color in android
  4. ActionBarDrawerToggle v7 arrow color
  5. Android Toolbar color change
  6. Android burger/arrow icon dynamic change color (это один работал в некоторым образом, но я не люблю использовать собственное изображение wihtout анимации).
    И другие ссылки, связанные с этой темой ... никто из них не работал для меня.

Что я делаю сейчас ищет ImageButton на панели инструментов (Get reference to drawer toggle in support actionbar), и применяя setColorFilter() ко всем из них как следующий код:

for (int i = 0; i < toolbar.getChildCount(); i++){ 
    if (toolbar.getChildAt(i) instanceof ImageButton) { 
     ImageButton ib = (ImageButton) toolbar.getChildAt(i); 
     ib.setColorFilter(Color.parseColor("#A74231"), PorterDuff.Mode.SRC_ATOP); 
    } 
} 

Я меняющегося цвет фона и текста: toolbar.setBackgroundColor и toolbar.setTitleTextColor.

Для иконок меню (в том числе значка меню переполнения):

MenuItem item2 = mMenu.findItem(R.id.actionbar_group_moreoverflow); 
item2.getIcon().setColorFilter(color, PorterDuff.Mode.SRC_ATOP); 


ВОПРОС: есть лучший способ сделать это (изменить панели инструментов элементов цвета динамически)?

ответ

4

Я был лицом к лицу проблема здесь. То, что я сделал для элементов панели инструментов:

  1. Для цвет фона: toolbar.setBackgroundColor(Color.parseColor("#xxxxxxxx"));
  2. Для цвета текста: toolbar.setTitleTextColor(Color.parseColor("#xxxxxxxx"));
  3. Для кнопки гамбургер/ящик:

    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. Для кнопок ActionMenuItemView (Панели инструментов включая кнопку перелива):

    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<View> 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. для деталей текста меню переполнения в: take a look at this link

+0

Я делаю что-то похожее на вас, основанное на ответе @ Шишрама. Но по-прежнему отсутствует способ раскрашивания фона и значков меню переполнения. – MiguelHincapieC

0

Чтобы получить все виды панели инструментов, проведите по всем его дочерним представлениям и раскрасьте их отдельно.Код петля для него выглядит следующим образом:

public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) { 
    final PorterDuffColorFilter colorFilter 
      = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.MULTIPLY); 

    for(int i = 0; i < toolbarView.getChildCount(); i++) { 
     final View v = toolbarView.getChildAt(i); 

     //Step 1 : Changing the color of back button (or open drawer button). 
     if(v instanceof ImageButton) { 
      //Action Bar back button 
      ((ImageButton)v).getDrawable().setColorFilter(colorFilter); 
     } 

     if(v instanceof ActionMenuView) { 
      for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) { 

       //Step 2: Changing the color of any ActionMenuViews - icons that 
       //are not back button, nor text, nor overflow menu icon. 
       final View innerView = ((ActionMenuView)v).getChildAt(j); 

       if(innerView instanceof ActionMenuItemView) { 
        int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length; 
        for(int k = 0; k < drawablesCount; k++) { 
         if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) { 
          final int finalK = k; 

          //Important to set the color filter in seperate thread, 
          //by adding it to the message queue 
          //Won't work otherwise. 
          innerView.post(new Runnable() { 
           @Override 
           public void run() { 
            ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter); 
           } 
          }); 
         } 
        } 
       } 
      } 
     } 

     //Step 3: Changing the color of title and subtitle. 
     toolbarView.setTitleTextColor(toolbarIconsColor); 
     toolbarView.setSubtitleTextColor(toolbarIconsColor); 

     //Step 4: Changing the color of the Overflow Menu icon. 
     setOverflowButtonColor(activity, colorFilter); 
    } 
} 

Во-вторых, реализовать метод, отвечающий за поиск и раскрашивание переливной Icon:

private static void setOverflowButtonColor(final Activity activity, final PorterDuffColorFilter colorFilter) { 
    final String overflowDescription = activity.getString(R.string.abc_action_menu_overflow_description); 
    final ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); 
    final ViewTreeObserver viewTreeObserver = decorView.getViewTreeObserver(); 
    viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      final ArrayList<View> outViews = new ArrayList<View>(); 
      decorView.findViewsWithText(outViews, overflowDescription, 
        View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION); 
      if (outViews.isEmpty()) { 
       return; 
      } 
      TintImageView overflow=(TintImageView) outViews.get(0); 
      overflow.setColorFilter(colorFilter); 
      removeOnGlobalLayoutListener(decorView,this); 
     } 
    }); 
} 

Toolbar цвет фона

mToolbarView.setBackgroundColor(color); 
ToolbarColorizeHelper.colorizeToolbar(mToolbarView, mToolbarIconsColor, getActivity()); 

взглянуть по этой ссылке, это может вам помочь https://snow.dog/blog/how-to-dynamicaly-change-android-toolbar-icons-color/

+0

Ty за ответ, но вы можете объяснить мне больше, как это собирается помочь мне с вопросом? (изменение динамически). Не знаю, если бы я был недостаточно ясен или в вашем ответе есть что-то, чего я не вижу, я имею в виду, я сказал динамично и без стиля. – MiguelHincapieC

+0

извините за то, что я удалил весь нежелательный код, проверьте ссылку в ответ, это может вам помочь! – Shishram

+0

уверен, я добавлю важные детали. – Shishram