1

I'm trying to populate a table at run time with Button elements, which I'm trying to apply a style defined in styles.xml to.

<style name="BlueButtonStyle">
    <item name="android:textSize">20sp</item>
    <item name="android:padding">15dp</item>
    <item name="android:layout_margin">5dp</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_weight">1</item>
    <item name="android:background">@drawable/gradient_button</item>
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:textAllCaps">false</item>
</style>

I'm already using this style on some static buttons where I'm able to define style="@style/BlueButtonStyle", so I know that the style itself works. It looks like this:

enter image description here

Buttons are generated in a loop like this:

val contextWrapper = ContextThemeWrapper(context, R.style.BlueButtonStyle)
val btn = Button(contextWrapper).apply { text = "Unknown" }

However, the result doesn't look the way it should:

enter image description here

The font color of #FFFFFF has been applied, but nothing else. It also doesn't have the same gray background that an unstyled button would have.

How do I properly style a programmatically generated Button? I was hoping to avoid having to inflate xml. Solution should be backwards compatible to min android 6.0.

user3340459
  • 435
  • 5
  • 13
  • 3
    `BlueButtonStyle` is not a theme. It's a style. (I know, it's confusing.) `ContextThemeWrapper` needs a theme. You'll need to pass the `R.style` for a theme of yours where you've set `@style/BlueButtonStyle`. You might also want to give `BlueButtonStyle` a parent, to take care of all the attributes you're not setting there; e.g. ` – Mike M. Oct 20 '18 at 20:20

1 Answers1

-1

I don't know kotlin, but in Java, you could do like this:

ContextThemeWrapper wrapper = new ContextThemeWrapper(this,R.style.BlueButtonStyle);
Button btn = new Button(wrapper, null, 0); // note this constructor
btn.setText("Unknown");
navylover
  • 12,383
  • 5
  • 28
  • 41