0

I was looking for how to create rounded buttons and it's simple enough. But I would like to be able to pass the color property to the drawable so that I can pass a different color for various buttons in the app instead of having to create a separate drawable xml for each color. In wpf we could reference the properties passed in using bindings, but I'm not sure what the proper method is in android.

button_rounded.xml

     <Button   
         color = "white"
         android:background="@drawable/rounded_button"
                        />

     <Button   
          color = "blue"
          android:background="@drawable/rounded_button"
                        />

I want to be able to pass the color from xml to the drawable rounded button so that I can maintain only one xml file. Is this possible in android?

James Joshua Street
  • 3,259
  • 10
  • 42
  • 80

1 Answers1

1

In Kotlin:

(yourButton.background as ShapeDrawable).paint.color = new_color_value

You can also adjust the ShapeDrawable before assigning to for a View.

val drawable = ContextCompat.getDrawable(context,R.drawable.your_shape) as ShapeDrawable
drawable.paint.color = your_another_color

Another way is using backgroundTint:

  <Button
      android: backgroundTint = "your_new_color"
      android: background = "@drawable/your_shape"
   />
TaQuangTu
  • 2,155
  • 2
  • 16
  • 30