Home > database >  how to set random color on a button in android
how to set random color on a button in android

Time:11-13

i am trying to make button which changes color when is pressed. i have tried to use

button!!.backgroundTintList = ColorStateList(
    arrayOf(intArrayOf(R.dimen.padding_large))
    intArrayOf(panit!!color)
)

and

button!!.setBacgroundColor(paint!!.color)

but button becomes like that in 100% of situations, even through paint.color is a random number each time enter image description here

CodePudding user response:

The 1st parameter of ColorStateList is an array of states.

You have to use something like:

    val colorList = ColorStateList(
        arrayOf(
            intArrayOf(android.R.attr.state_pressed),  // Pressed
            intArrayOf(android.R.attr.state_enabled),  // Enabled
            intArrayOf()
        ),
        intArrayOf(
            Color.BLUE,      // The color for the Pressed state
            Color.BLACK,     // The color for the Enabled state
            Color.RED        // The color for the Disabled state
        )
    )

    button.backgroundTintList = colorList
  • Related