I am using a built-in theme for my Android app:
<style name="AppTheme" parent="android:Theme.Black"> <!-- Customize your theme here. --> </style>
I am happy with that theme, except I want to change the background color of a button. Here is how it looks by default:
Here’s what happens when I add a background color to this button (
Hey!? It basically changed all the button’s size, padding and margins!
So I managed to get the expected result using the
backgroundTint property (
Unfortunately, this is only supported since version 21 of the API, which is not acceptable for me.
So two questions:
- Why does changing the background messes with the rest of the button’s properties?
- How do I get the expected result without
And a bonus question: How can I get the expected result programmatically (I have dynamic buttons in my app, so this would be very useful)?
You can change this color in your Java File. When your main class loads you can take an object of this button and then change color.
Here is how you define this button in Manifest file :
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="PLAY" android:id="@+id/btn1" ... />
Now in your Java file when you are adding this XML layout you need to
Button b = (Button)findViewByID(R.id.btn1); b.getBackground().setColorFilter(0xFFFF0000,PorterDuff.Mode.MULTIPLY);
You may also use COLOR:
The code below sometimes does not work for me :-
In my case I will be doing in this process
<Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="3dp" android:background="@color/play_as" android:padding="8dp" android:text="Button" />
Or you can use this link which is more easy way of creating the buttons