以编程方式设置工具栏图标颜色 [英] Set Toolbar Icon Colour Programmatically

查看:104
本文介绍了以编程方式设置工具栏图标颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过编程方式设置Toolbar/AppBarLayout 中的图标(主页和溢出菜单图标)的颜色?

How can I set the colour of icons (home and overflow menu icon) in a Toolbar/AppBarLayout programmatically?

我想更改活动中单个片段的工具栏的配色方案.将AppBarLayout的背景设置为浅色(例如,带有appBarLayout.setBackgroundResource(..);的浅灰色)会产生几乎看不见的白色图标和白色标题.

I want to change the toolbar's colour scheme for a single fragment in an activity. Setting the AppBarLayout's background to a light colour (e.g. light gray with appBarLayout.setBackgroundResource(..);) results in white icons and a white title which are barely visible.

其布局如下:

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:theme="@style/ToolbarStyle"
        app:layout_scrollFlags="scroll|enterAlways"/>

</android.support.design.widget.AppBarLayout>


找到解决方案


Solution found

推荐答案

通过支持23可以轻松更改溢出图标.这是洛恩·拉利伯特(Lorne Laliberte)的答案

Change overflow icon is easy with support 23. Here is a method from Lorne Laliberte answer

public static void setOverflowButtonColor(final Toolbar toolbar, final int color) {
    Drawable drawable = toolbar.getOverflowIcon();
    if(drawable != null) {
        drawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTint(drawable.mutate(), color);
        toolbar.setOverflowIcon(drawable);
    }
}

您可以通过自定义可绘制对象来更改房屋..

You can change your home as up passing your custom drawable..

getSupportActionBar().setHomeAsUpIndicator(R.drawable.your_drawable)

或更改其颜色

final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(Color.parseColor("#FFFFFF"), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);

如果您想更改更多元素,请此处是更改所有工具栏图标颜色的好方法.

If you want to change more elements here is good post to change all toolbar icons colors.

希望这会有所帮助!

这篇关于以编程方式设置工具栏图标颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆