Lance Samaria
Lance Samaria

Reputation: 19592

Kotlin -How to Change the Color Tint of an Image inside a Button to Another Color Tint and Back

I have a button that has a red and black image inside of it. When the button is pressed I want to change the color of the image tint to gray and when it is pressed again I want to remove the gray color. The image tine should go back to its original color.

XML:

<Button
    android:id="@+id/camera_button"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:background="@drawable/red_and_black_camera_button_icon"
/>

Activity:

var changeColor = false

fun cameraButtonTapped() {

   changeColor = !changeColor

   // I know this doesn't work. This is one of the many ways I tried
   binding.camera_button.backgroundTintList = if(changeColor) ColorStateList.valueOf(ContextCompat.getColor(this, R.color.gray)) else null
}

Upvotes: 0

Views: 440

Answers (3)

Lance Samaria
Lance Samaria

Reputation: 19592

1- To get around this issue I used an ImageView instead and set its src property to the camera button image:

XML:

<ImageView
    android:id="@+id/camera_button_iv"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:src="@drawable/red_and_black_camera_button_icon"
/>

2- In res/colors I added a clear color

<color name="clearColor">#00000000</color>

3- In the Activity I toggle the imageView's .setColorFilter() to either color. This changes the image's tint color to gray and when the clearColor is added it goes back to red and black.

var changeColor = false

fun cameraButtonTapped() {

   changeColor = !changeColor

   val grayColor = ContextCompat.getColor(binding.root.context, R.color.gray)
   val clearColor = ContextCompat.getColor(binding.root.context, R.color.clearColor)

   binding.camera_button_iv.setColorFilter(if (changeColor) grayColor else clearColor)
}

Upvotes: 0

Hossein S
Hossein S

Reputation: 22

var flag=false 

btn.setOnClickListener{
 flag=!flag
 if(flag)
    it.setBackgroundColor(Color.GREEN)
 else
    it.setBackgroundColor(Color.GRAY)
}

Upvotes: -1

Dmitry
Dmitry

Reputation: 1

I think that the image should initially be white,

<ImageButton
            android:id="@+id/camera_button"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:src="@drawable/red_and_black_camera_button_icon"
            app:tint="@color/red"/>

and then you set the desired color like this

binding.camera_button.setColorFilter(Color.GRAY)

Upvotes: -1

Related Questions