0

Here is what the button looks like after changing the color

Here is what it looks like with "show layout bounds" on

I have an "add note" button which shows a dialog for the user to enter a note.

I want to change the color of the button if a note is saved.

I've tried this:

btnNote.setBackgroundColor(view.getContext().getResources().getColor(R.color.NN));

and this:

btnNote.getBackground().setColorFilter(ContextCompat.getColor(view.getContext(), R.color.NN), PorterDuff.Mode.MULTIPLY);

But in both cases the button also becomes slightly bigger.

How can I change only the color of the button?

this is my button from my layout file:

<Button
    android:id="@+id/btnNote"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:text="Add note"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/btnDelete"
    app:layout_constraintTop_toTopOf="parent" />

4 Answers4

1

I have tried all options and finally its working properly when, I Use android:backgroundTint attribute in your XML Button View.

Show below Snippet:-

android:backgroundTint="#6567dc"

Problematically

If in your gradle file minSdkVersion is below 21 than you should change it to 21 OR you can wrap code in to if condition that check device SDK support as below

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            btnAccept.setBackgroundTintList(ContextCompat.getColorStateList(this, R.color.yourcolor));
        }

using above code output:

enter image description here

After color changed

enter image description here

ND1010_
  • 3,743
  • 24
  • 41
Janvi Vyas
  • 732
  • 5
  • 16
0

Instead of using background , try backgroundTint

In xml,

android:backgroundTint="#yourcolor"

in java,

setBackgroundTintList(ColorStateList list)

For AppCompatButton ,

button.setSupportBackgroundTintList(ContextCompat.getColorStateList(this, R.color.yourcolor));

You can use ,

 ViewCompat.setBackgroundTintList(AppCompatButton, ColorStateList)
Jyoti JK
  • 2,141
  • 1
  • 17
  • 40
0

I think it dosen't become bigger,you can open the switch named "show layout bound" in developer option,the button's layout has not been changed,you can custom an drawable as the background.

  • I tried that, and you are right that the bounds do not become bigger (See the 2nd screenshot I added to the question). But the button does become bigger when the color is changed –  Apr 28 '18 at 06:55
  • I'll make a custom drawable for the background and check the result –  Apr 28 '18 at 06:58
  • Thanks, that is the solution –  Apr 28 '18 at 08:22
0

You can use background and don't use colour instead use drawable with different colours as you are using shape as background and setting colour to it does changes the colour but shape is not maintained so you need to add drawable shape with the colour you want to change

Sai Kishen
  • 46
  • 5