Home > Blockchain >  Android. How to programatically change background color of button
Android. How to programatically change background color of button

Time:11-26

I need to create Button programatically. And my button can be randomly colored. However, I need to set the background color of the button and also the background color when the button is in a state PRESSED.

That is, the background color of the button in its normal state should be different from the background color when the user pressed the button.

For example, when I need a different background for a button, depending on the state, I use a selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/shape_not_pressed" android:state_pressed="false" />
    <item android:drawable="@drawable/shape_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/shape_not_pressed" />
</selector>

And in my xml for button:

  android:background="@drawable/selector_button"

This is a working solution if you know the background you need in advance. However, in my case, I am dynamically getting the background for the button (pressed_bg and not_pressed_bg) and therefore this method does not work for me. Is it possible to implement this programmatically?

P.S. I need pressed effect

Please, help me.

CodePudding user response:

You can programaticaly check and set the colors like this.

if(someButton.isPressed){
     val pressedRandomColor = getPressedRandomColor()
     someButton.setBackgroundColor(pressedRandomColor)
 }else {
     val randomColor = getRandomColor()
     someButton.setBackgroundColor(randomColor)
 }

The logic for getPressedRandomColor() and getRandomColor() you need to define by yourself, it should return Int value.

CodePudding user response:

You can create a color code list and pass the color code randomly on a button click to set button background color.

yourButton.setBackgroundColor(Color.parseColor("#0060AB"));
  • Related