0

Is there a way to take a programmatically-created button (not defined in XML) and shrink it so it matches the size of its text?

Essentially I want these buttons to be much smaller:

buttons

I have tried setting minWidth and minHeight to 0, to no avail:

val btn = Button(view.context)
btn.text = getTranslationLabel(t)
btn.minWidth = 0
btn.minHeight = 0
translationsHolder.addView(btn)
knpwrs
  • 15,691
  • 12
  • 62
  • 103
  • Size is determined mostly by the `LayoutParams` that you could be passing in [the second parameter to `addView()`](https://developer.android.com/reference/android/view/ViewGroup#addView(android.view.View,%20android.view.ViewGroup.LayoutParams)). The type of the `LayoutParams` subclass would be based on the type of the `ViewGroup` you are adding it to. In this case, you are probably also getting some minimum padding created by the button background; you may need to switch to a custom background. – CommonsWare Sep 02 '20 at 00:16
  • Did you try setting the padding of the button to zero? – Muddassir Ahmed Sep 02 '20 at 01:20
  • @CommonsWare in my full code I actually have the background set to null, I put the background back for the sake of the screenshot, but good to know otherwise. I’ll try your other suggestions, thanks! – knpwrs Sep 02 '20 at 10:55
  • @MuddassirAhmed yes, I tried setting padding to 0 to no avail. – knpwrs Sep 02 '20 at 10:55

1 Answers1

1

So after some experimentation and searching was able to find this answer and it works https://stackoverflow.com/a/41525925/5841416. You need to set both minHeight and minimumHeight attributes.

button.minWidth = 0
button.minHeight = 0

button.minimumWidth = 0
button.minimumHeight = 0
Muddassir Ahmed
  • 518
  • 4
  • 19