简体   繁体   English

在Android中以编程方式更改可绘制颜色

[英]change a drawable color programmatically in android

i have the following parallelogram shape : 我有以下平行四边形形状:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="200dp"
    android:height="50dp"
    android:viewportWidth="200"
    android:viewportHeight="50">

    <path android:fillColor="#000000"
    android:pathData="M 200 0 L 20 0 L 0 50 L 180 50 L 200 0" />
</vector>

and i have used it in this way 我已经用这种方式

    <View

        android:layout_width="66dp"
        android:layout_height="26dp"
        android:layout_centerInParent="true"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="112dp"
        android:background="@drawable/shape"
        android:onClick="test"
        android:tag="p112"
        app:layout_constraintHorizontal_bias="0.615"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

now i want to change its color from black to white after tapping. 现在,我想在点击后将其颜色从黑色更改为白色。 function "test" would trigger after touching. 触摸后会触发“测试”功能。 but all i have found changes the color of background that would make my black parallelogram to a white rectangle. 但是我发现的所有内容都会改变背景颜色,使我的黑色平行四边形变为白色矩形。 is there any way i can change its color. 有什么办法可以改变它的颜色。 even manipulating the xml would be fine. 甚至操作xml也可以。 tnx n

test function: 测试功能:

    public void test(View view){
        view.setBackgroundColor(Color.WHITE);
    }

Drawable backgroundDrawable = DrawableCompat.wrap(view.getBackgroundDrawable()).mutate(); DrawableCompat.setTint(backgroundDrawable, color); You can use this!! 你可以用这个!

Try using setBackgroundTint instead of color. 尝试使用setBackgroundTint代替颜色。 that should alter the resource of the background. 应该会改变背景资源。

You cannot change the color of individual path at runtime. 您不能在运行时更改单个路径的颜色。 You can however , change the color of entire vector. 但是,您可以更改整个矢量的颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM