Reputation: 59960
I create android button programmatically, and I put this butons in a TableRow, every thing work fine, but when I change the backgroudColor the colored button not respect the size as it do without the color:
My code is:
val btn = Button(this)
btn.isEnabled = false
btn.setBackgroundColor(Color.RED)
btn.layoutParams = TableRow.LayoutParams(150, 150)
When I don't use the setBackgroundColor
the size is correct.
I don't understand why the size is changes, is there any way to change only the default gray color of the button, without the size is changes.
Upvotes: 0
Views: 353
Reputation: 9872
The default background for a button is not a solid color, but is rather a graphic (e.g. a nine-patch bitmap) that has paddings and margins built into it. Thus, when you replace that background image with a color, all of the built-in paddings and margins are thrown away.
Instead of setting a background color with setBackgroundColor()
you could try using setBackgroundTintList()
which should tint the existing background image with your chosen color(s).
Alternatively, you would need to manually set the margins and paddings after changing the background to the solid red color, something that is much more painful to do via code than it is in a layout XML file.
Example layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red Button"
android:backgroundTint="#a00"
android:textColor="#fff" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Default Button" />
</LinearLayout>
Upvotes: 1
Reputation: 2814
if your app theme
is material-theme
then there is a default paddings applied to the button. that's why the color fills the whole canvas of the button after you apply it. try to restore the padding (I believe it's 8dp for all edges).
Upvotes: 1