Home » Android » java – Android button background color changes button size

java – Android button background color changes button size

Posted by: admin June 15, 2020 Leave a comment

Questions:

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:

default

Here’s what happens when I add a background color to this button (android:background="@color/play_bg"):

enter image description here

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"):

enter image description here

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)?

How to&Answers:

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)

Answer:

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