以编程方式更改android按钮可绘制图标的颜色 [英] Change android button drawable icon color programmatically

查看:82
本文介绍了以编程方式更改android按钮可绘制图标的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式从按钮更改图标颜色...

I want to change my icon color from my button programmatically...

在我的xml上,我有:

On my xml, i have:

            android:drawableTint="@color/colorPrimary"
            android:drawableTop="@drawable/ic_car_black_24dp"

要设置图标并设置图标颜色...但是我想从Java端更改图标颜色...

To set the icon and set the icon color... But i want to change the icon color from my java side...

有人可以帮助我吗?

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/bt_search_vehicle_car"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/eight_density_pixel"
            android:layout_weight="1"
            android:background="@drawable/background_rounded_blue_border"
            android:drawableTint="@color/colorPrimary"
            android:drawableTop="@drawable/ic_car_black_24dp"
            android:padding="@dimen/eight_density_pixel"
            android:text="Carros"
            android:textAllCaps="false"
            android:textColor="@color/colorPrimary" />

推荐答案

首先,除非编写自定义视图并要扩展它,否则不要直接使用 AppCompatButton .正常的 Button 将由系统解析为" AppCompatButton ,因此您不需要后者.

First of all, do not use AppCompatButton directly unless you write a custom view and you want to extend it. The normal Button will be "resolved" by the system as AppCompatButton so you don't need the latter.

对于您的原始问题,有多种着色可绘制对象的方法.您可以使用 DrawableCompact 以着色"方式进行操作,同时可以使用常规的 ColorFilter 以过滤"方式执行此操作.

As for your original question, there are multiple ways to tint a drawable. You can use DrawableCompact to do it in a "tinting" fashion while you can use a normal ColorFilter to do this in a "filtering" fashion.

使用 DrawableCompat

Use DrawableCompat to wrap the drawable so it can be tinted on older platforms.

Button yourButton = findViewById(R.id.bt_search_vehicle_car);

Drawable drawable = getResources().getDrawable(R.drawable.ic_car_black_24dp);
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.colorPrimary));

yourButton.setCompoundDrawables(null, drawable, null, null);

使用 ColorFilter

使用 Drawable.setColorFilter(...) 方法为可绘制对象设置覆盖滤色器.

Using ColorFilter

Use the Drawable.setColorFilter(...) method to set an overlaying color filter for your drawable.

Button yourButton = findViewById(R.id.bt_search_vehicle_car);

Drawable drawable = getResources().getDrawable(R.drawable.ic_car_black_24dp).mutate();
drawable.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.SRC_ATOP);

yourButton.setCompoundDrawables(null, drawable, null, null);

这篇关于以编程方式更改android按钮可绘制图标的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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