Omar Omar - 5 months ago 41
Android Question

Change BackgroundTint of ImageView on Android

I have an ImageButton which have a drawable background resource which is oval shape.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:angle="270"
android:color="#FFFF0000" />

</shape>




Here is the ImageButton in XML:

<ImageButton
android:id="@+id/c1"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_columnSpan="1"
android:layout_rowSpan="1"
android:background="@drawable/circle"
android:layout_margin="10dp"
/>


I need to change the color of the circle shape dynamically, this will be done by either change the backgroundTint property in the ImageButton or change the circle shape color.

NOTE:
I have array of strings that stores a list of RGB colors i need to use these RGB colors.

Answer

i just found the answer, it works as follow: In my changeColors(int id) function

  • Create ImageButton variable.
  • Assign the passed id to the ImageButton variable.
  • Define GradientDrawable variable to store the ImageButton background.
  • Update the color of the background using GradientDrawable variable.
  • Update the ImageButton to the new background.

This is the code:

  ImageButton circle;
        circle = (ImageButton) findViewById(id);
        GradientDrawable drawable = (GradientDrawable) getResources().getDrawable(R.drawable.circle);
        drawable.setColor(Color.parseColor("color in format #FFFFFF");
        circle.setBackground(drawable);
Comments