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 (android:background="@color/play_bg"
):
Hey!? It basically changed all the button's size, padding and margins!
So I managed to get the expected result using the backgroundTint
property (android:backgroundTint="@color/play_bg"
):
Unfortunately, this is only supported since version 21 of the API, which is not acceptable for me.
So two questions:
backgroundTint
?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)?
To set Android Button background color, we can assign android:backgroundTint XML attribute for Button in layout file with the required Color Value. To programmatically set or change Android Button background color, we may call pass the method Button.
How to Change the Background Color of Buttons. To change the background color of the button, use the CSS background-color property and give it a value of a color of your taste. In the . button selector, you use background-color:#0a0a23; to change the background color of the button.
Color 2 button shows the background colour.
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: COLOR.RED The code below sometimes does not work for me :- b.setBackgroundColor(int color)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With