user5210131
user5210131

Reputation:

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. tnx

test function:

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

Upvotes: 2

Views: 11999

Answers (3)

Barış S&#246;be
Barış S&#246;be

Reputation: 468

Drawable backgroundDrawable = DrawableCompat.wrap(view.getBackgroundDrawable()).mutate(); DrawableCompat.setTint(backgroundDrawable, color); You can use this!!

Upvotes: 9

user6547359
user6547359

Reputation: 204

Try using setBackgroundTint instead of color. that should alter the resource of the background.

Upvotes: 0

Dishonered
Dishonered

Reputation: 8831

You cannot change the color of individual path at runtime. You can however , change the color of entire vector.

Upvotes: 1

Related Questions