'Changing button color causes the button to get bigger
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" />
Solution 1:[1]
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.
Solution 2:[2]
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:
After color changed
Solution 3:[3]
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)
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Feng Jian |
Solution 2 | ND1010_ |
Solution 3 | |
Solution 4 | Sai Kishen |