0
mButton.setBackgroundColor(Color.GREEN) ;

So, I used that method to change the color of a button when it's clicked. Button was initialized like private in MainActivity and this in onCreate():mButton = (Button) findViewById( R.id.button_count); I tried to cast it to View and still doesn't work. Maybe, it can help you - when I set any color in Attribute Pane attribute background, color of a button doesn't change.

I want to know how to change background color in java code or what's wrong with my program. Thank you

Machavity
  • 30,841
  • 27
  • 92
  • 100
  • That is probably a variation on [this problem](https://stackoverflow.com/q/64722733/115145). – CommonsWare Feb 13 '21 at 12:54
  • 3
    Does this answer your question? [Android button background color](https://stackoverflow.com/questions/18070008/android-button-background-color) – Style-7 Feb 13 '21 at 13:13
  • can you show a log of your android studio or your code ? – Aadesh Mishra Feb 13 '21 at 14:46
  • 1
    This [edit](https://stackoverflow.com/posts/66185313/timeline#history_491c0994-5248-4f24-8ca4-c7fb00679bfd) to the question completely changes the question and renders the existing answers and discussion confusingly off topic. – Jon Apr 20 '21 at 18:20
  • @Jon is absolutely correct; I've rolled back the edit. – Ryan M Apr 21 '21 at 08:28
  • @Jon what do you know about ban in stackoverflow?) –  Apr 29 '21 at 10:47

2 Answers2

0

Try with this line:

mButton.setBackgroundColor(getResources().getColor(R.color.Green));

Note : Green color defined in color.xml

Shay Kin
  • 2,539
  • 3
  • 15
  • 22
Mohit Kumar
  • 41
  • 1
  • 7
0

button.setcolorfilter(Color) was deprecated in API 29.

button.setBackgroundColor(color) messes with the button style.

So here is a new way to do this using BlendModeColorFilter(): https://developer.android.com/reference/android/graphics/BlendModeColorFilter

See the above link for documentation.

fun setButtonColor(btn: Button, color: Int) {
    if (Build.VERSION.SDK_INT >= 29)
        btn.background.colorFilter = BlendModeColorFilter(color, BlendMode.MULTIPLY)
    else
        btn.background.setColorFilter(color, PorterDuff.Mode.MULTIPLY)
}

According to the new APIs, color filters work fine.

Kirby
  • 15,127
  • 10
  • 89
  • 104