【问题标题】:Changing Android Toolbar DrawerArrowToggle color更改 Android 工具栏 DrawerArrowToggle 颜色
【发布时间】:2015-03-30 12:47:51
【问题描述】:

我在我的项目中使用 Appcompat 7 作为带有导航切换的工具栏。除了要求在每个活动或片段发生变化时动态更改 DrawerArrowToggle 图标的颜色之外,一切正常。

我的styles.xml文件代码如下:

<style name="NavigationTheme" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">#FFFFF</item>
        <item name="colorPrimaryDark">#F2F2F2</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>


<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">false</item>
        <item name="color">#FFFFFF</item>
    </style>


在上述样式文件中,我使用了 DrawerArrowToggle 颜色作为 White,但我的要求是在运行时更改为其他颜色。我没有发布任何代码,因为我完全被卡住了,我什至找不到一条代码来满足我的要求。

【问题讨论】:

  • 只需使用(在 kotlin 中)`toolbar.navigationIcon?.apply { if (this is DrawerArrowDrawable) color = /*yourColor*/}`我知道这是一个迟到的答案,但以防万一有人需要将来会。

标签: android menuitem material-design android-toolbar drawertoggle


【解决方案1】:

我不确定这是否可行,我还没有测试过自己。

首先获取导航图标的view reference:

 public static View getToolbarNavigationIcon(Toolbar toolbar){
        //check if contentDescription previously was set
        boolean hadContentDescription = TextUtils.isEmpty(toolbar.getNavigationContentDescription());
        String contentDescription = !hadContentDescription ? toolbar.getNavigationContentDescription() : "navigationIcon";
        toolbar.setNavigationContentDescription(contentDescription);
        ArrayList<View> potentialViews = new ArrayList<View>();
        //find the view based on it's content description, set programatically or with android:contentDescription
        toolbar.findViewsWithText(potentialViews,contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
        //Nav icon is always instantiated at this point because calling setNavigationContentDescription ensures its existence 
        View navIcon = null;
        if(potentialViews.size() > 0){
            navIcon = potentialViews.get(0); //navigation icon is ImageButton
        }
         //Clear content description if not previously present
        if(hadContentDescription)
            toolbar.setNavigationContentDescription(null);
        return navIcon;
     }

一旦您获得视图引用,将ColorFilter 应用到可绘制对象,在这种情况下是 ActionBarDrawerToggle 图标:

View navigationIcon = getToolbarNavigationIcon(mToolbar);
Drawable navDrawable = navigationIcon.getDrawable();
if(navDrawable != null){
   navDrawable.setColorFilter(newColor, PorterDuff.Mode.MULTIPLY);
}

【讨论】:

  • 从可访问性的角度来看,清除内容描述是个坏主意。也许你可以使用视图的标签来存储一些东西来表明它已经被改变了?
  • 确实如此。如果之前未设置,则会在此 sn-p 中清除 contentDescription。
猜你喜欢
  • 1970-01-01
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多