androidbuttonandroid-appcompatandroid-buttonandroid-theme

Programmatically created button doesn't follow theme's button style


The buttons created programmatically don't follow the buttonStyle defined in the apptheme, but the buttons created in xml follow it.

Below is my style.xml

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="buttonStyle">@style/Button.Primary</item>
    </style>

    <style name="Button.Primary" parent="Widget.AppCompat.Button.Colored">
        <item name="textAllCaps">true</item>
        <item name="android:textColor">#fff</item>
        <item name="backgroundTint">@color/btn_bck</item>
    </style>

And this is how I create a button programmatically:

Button progBtn = new Button(this);
progBtn.setText("Programmatic button");
LinearLayout layout = findViewById(R.id.container);
layout.addView(progBtn);

And it shows up as the default gray colored background with black text color.

But if I use the button in xml like:

<Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

It works fine and shows up with white text color and the correct backgroundTint specified in style.

I'd like to know why is there an inconsistency in the button style between the above 2 methods of button creation?


Solution

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

    You can use:

    Button progBtn = new AppCompatButton(this);
    progBtn.setText("Programmatic button");
    LinearLayout layout = findViewById(R.id.container);
    layout.addView(progBtn)
    

    enter image description here