Why is the style of my programmatically created button different?

Viewed 50

Starting with a new project in Android Studio with an empty Activity, I add a linear layout with a single button in activity_main.xml:

<LinearLayout
    android:id="@+id/buttons"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Demo01" />
</LinearLayout>

then in my MainActivity, I programmatically add a second button:

val buttonsLayout = findViewById<LinearLayout>(R.id.buttons)
val button = Button(this)
button.layoutParams = ViewGroup.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT,
    ActionBar.LayoutParams.WRAP_CONTENT
)
button.text = "Demo 01"
buttonsLayout.addView(button)

Finally when I run this app, I see this:

buttons with different colors

The first and second buttons seem to have different styles.

Why are they different? Furthermore, what's the correct way to programmatically create new views so that the programmatically created views have the same style as their xml layout counterparts?

1 Answers

They are different because you are using a Theme.MaterialComponents.* theme.
With this theme the Button defined in the layout is replaced at runtime by a MaterialButton.

To have the same button you have to use:

    val buttonsLayout = findViewById<LinearLayout>(R.id.buttons)
    val button = MaterialButton(this)
    //...
    button.text = "Demo01"
    buttonsLayout.addView(button)

enter image description here

Related