问题
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:
- Why does changing the background messes with the rest of the button's properties?
- How do I get the expected result without
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)?
回答1:
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)
回答2:
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
来源:https://stackoverflow.com/questions/31008279/android-button-background-color-changes-button-size