androidkotlin

How do I make a button randomly change it's background color every click?


Started Android and can't figure out how to make the button's background color change randomly every click without setting the backgroundTint(for drawable layer issues)? let's say my button's drawable is really fashioned and has layers on top of it. If i change the backgroundTint then it would draw all over my button. what If I wanted to change the bottom layer's background color? would I have to create a drawable programmatically and apply it to the button every time?


Solution

  • Are you trying to randomly change the color of a specific layer inside a LayerDrawable? If so, you can find the target drawable within the LayerDrawable either by index (getDrawable(int index)) or by ID (findDrawableByLayerId(int id)), and then change its color using setTint(int tintColor). If your LayerDrawable is created in XML, you can directly assign an ID to each layer like this:

    <item
        android:id="@+id/background_layer"
        android:drawable="@drawable/bottom_background_drawable" />