How to change color of vector drawable path android programmatically

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context="quizcounter.compete.geeks.vectordrawablecolorchange.MainActivity">

    <Button
        android:layout_marginTop="10dp"
        android:id="@+id/button"
        android:text="Change Color"
        android:layout_width="wrap_content"
        android:layout_marginBottom="30dp"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:drawableRight="@drawable/ic_settings_black_24dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</LinearLayout>
MainActivity.java

package quizcounter.compete.geeks.vectordrawablecolorchange;

import android.graphics.drawable.Drawable;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button button;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView=findViewById(R.id.text);
        button=findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

               // Take vector drawable you want to set to textview
                Drawable vectorDrawable = VectorDrawableCompat.create(
                        getResources(),
                        R.drawable.ic_settings_black_24dp,
                        null);
                Drawable drawable = DrawableCompat.wrap(vectorDrawable);

               // Change color o Vector drawable to colorAssent                 DrawableCompat.setTint(drawable.mutate(),getResources().getColor(R.color.colorAccent));

               //set vector as right drawable
                textView.setCompoundDrawablesWithIntrinsicBounds(null, null,drawable, null);

                textView.setTextColor(getResources().getColor(R.color.colorAccent));
            }
        });


    }
}



No comments:

Post a Comment

Popular Posts