'Dynamically created button doesn't apply style correctly

I defined a style in themes.xml:

<style name="ButtonStyle" parent="Widget.MaterialComponents.Button">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">240dp</item>
</style>

I then apply it to some of the buttons, in activity_main.xml:

<Button
    android:id="@+id/btn_folder0"
    style="@style/ButtonStyle"
    android:text="@string/folder0" />

<Button
    android:id="@+id/btn_folder1"
    style="@style/ButtonStyle"
    android:text="@string/folder1" />

Now I want to dynamically create a button and apply the same style, like this (in MainActivity.kt):

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val layout = findViewById<LinearLayout>(R.id.layout_folders)
    val btn = Button(this, null, R.style.ButtonStyle)
    btn.text = "new button"
    layout.addView(btn)
}

However the dynamically created button doesn't have the style. It looks like:

enter image description here

I have also tried val btn = Button(ContextWrapper(this, R.style.ButtonStyle)) which leads to a different result but again not the same style as the upper two buttons.

What am I missing? How can I apply the style to a dynamically created button?



Solution 1:[1]

You are creating the button using Button(Context context, AttributeSet attrs, int defStyleAttr)

According to the docs:

This constructor allows a Button subclass to use its own class-specific base style from a theme attribute when inflating.

To apply your style to the button, you should use Button(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) instead.

Solution 2:[2]

Width and height can't be set via themes at runtime. You need to set them in layout params, and use that when you add it to the parent view.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iLittleWizard
Solution 2 Gabe Sechan