Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

android - MenuItem tinting on AppCompat Toolbar

When I use drawables from the AppCompat library for my Toolbar menu items the tinting works as expected. Like this:

<item
    android:id="@+id/action_clear"
    android:icon="@drawable/abc_ic_clear_mtrl_alpha"  <-- from AppCompat
    android:title="@string/clear" />

But if I use my own drawables or actually even copy the drawables from the AppCompat library to my own project it will not tint at all.

<item
    android:id="@+id/action_clear"
    android:icon="@drawable/abc_ic_clear_mtrl_alpha_copy"  <-- copy from AppCompat
    android:title="@string/clear" />

Is there some special magic in the AppCompat Toolbar that only tint drawables from that library? Any way to get this to work with my own drawables?

Running this on API Level 19 device with compileSdkVersion = 21 and targetSdkVersion = 21, and also using everything from AppCompat

abc_ic_clear_mtrl_alpha_copy is an exact copy of the abc_ic_clear_mtrl_alpha png from AppCompat

Edit:

The tinting is based on the value I have set for android:textColorPrimary in my theme.

E.g. <item name="android:textColorPrimary">#00FF00</item> would give me a green tint color.

Screenshots

Tinting working as expected with drawable from AppCompat Tinting working as expected with drawable from AppCompat

Tinting not working with drawable copied from AppCompat Tinting not working with drawable copied from AppCompat

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After the new Support library v22.1, you can use something similar to this:

  @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        Drawable drawable = menu.findItem(R.id.action_clear).getIcon();

        drawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTint(drawable, ContextCompat.getColor(this,R.color.textColorPrimary));
        menu.findItem(R.id.action_clear).setIcon(drawable);
        return true;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...