-5

I fail changing the background of my button in my activity. It is a basic button which a shape as a background.

In my main.xml it looks like this in my RelativeLayout:

<Button
    android:id="@+id/mybtn"
    android:background = "@drawable/rounded_button"
    android:elevation="0dp" />

In my MainActivity I try to change the button like this:

    Button btn = findViewById(R.id.mybtn);
    btn.setBackgroundColor(Color.RED);

But it says:

cannot resolve method setBackgroundColor

Jon not doe xx
  • 533
  • 3
  • 10
  • 20

5 Answers5

0

Try this:

Button b = ...;
int color = ...;
...
CompoundButtonCompat.setButtonTintList(button, ColorStateList.valueOf(color));

Compat libraries checks compatibility and remove most of issues that come with android fragmentation.

You can try to set background by calling compatibility library with set background color method, but I prefer and probably a common usage is to call tint methods on a components that comes from appcompat and a material design library.

Hope this helps.

BR

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Milan Jurkulak
  • 557
  • 3
  • 6
0

You have to change the background of your drawable I guess

Drawable mDrawable = AppCompatResources.getDrawable(context, R.drawable. rounded_button); 
Drawable wrappedDrawable = DrawableCompat.wrap(mDrawable);
DrawableCompat.setTint(wrappedDrawable, Color.RED);   
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
0

You have to change the setBackgroundColor to setBackground.

Button btn = findViewById(R.id.mybtn); btn.setBackground(Color.RED);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
0

You have to change the setBackgroundColor to setBackground.

Button button= findViewById(R.id.mybtn);

Try this below code

button.setBackgroundResource(ContextCompat.getColor(MainActivity,this,R.color.red));
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
0

you can try this

button.setBackgroundDrawable(ContextCompat.getDrawable(context , active ? R.drawable.gray_schedule_button : R.drawable.curved_button_shape ));
Vivek Pratap Singh
  • 1,564
  • 16
  • 26