Lina
Lina

Reputation: 563

Change the background tint with kotliin

I create an Android App with Kotlin, I have the following problem : In one of my UI, I create a constraint layout which has the following :

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="35dp"
    android:layout_height="35dp"
    android:layout_marginTop="5dp"
    android:layout_marginEnd="5dp"
    android:id="@+id/cart"
    android:background="@drawable/circle_vs_shape"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <ImageView
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginStart="5dp"
        android:layout_marginTop="5dp"
        android:layout_marginEnd="5dp"
        android:layout_marginBottom="5dp"
        android:tint="@color/whiteFour"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/add_cart" />
</androidx.constraintlayout.widget.ConstraintLayout>

I want to change the background tint of this constraint layout when I click on.In the setonclickListener of this constraint I add the following code but it didn't change

 constraint.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#FF8800"))

How can I correct my code, to change the backgound tint color?

Upvotes: 0

Views: 2538

Answers (1)

DemoDemo
DemoDemo

Reputation: 392

Personally there are several ways to fix this:

    ConstraintLayout someLayout=(ConstraintLayout)view.findViewById(R.id.someLayout);
    someLayout.getBackground().setColorFilter(Color.parseColor("#ff8800"), PorterDuff.Mode.SRC_ATOP);

If it's an aregular asset (the background is an image and not vector) you could create a color selector in the color folder.

You could also use two Images which will have a different image and a different tint color instead of a container and an imageview.

Edit

place it in the color folder

email_phone_color_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="@color/sms_phone_disabled"/>
    <item android:state_pressed="true" android:color="@color/sms_phone_disabled"/>
    <item android:color="@color/sms_phone_enabled"/>
</selector>

And use it

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cart"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_width="35dp"
    android:layout_height="35dp"
    android:layout_marginTop="5dp"
    android:background="@color/email_phone_color_selector"
    app:tint="@color/colorAccent">

Upvotes: 2

Related Questions