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?
Button
constructor that doesn't include any styled attributes; you want the overloaded constructor that accepts them; Edit: it's also not inheriting the default button style because you're defining the attribute for anAppCompatButton
(buttonStyle
vsandroid:buttonStyle
) but then using aButton
– Lunenew Button(this, null, R.attr.buttonStyle);
( though I'm not really sure if this is the correct way to use it), but it still doesn't really work as expected. It does apply the style but the background color is not the same. It's using color accent as background color. – EarlbackgroundTint
instead ofandroid:backgroundTint
), which the defaultButton
doesn't use. You either need to use the android style declaration (android:xxxx
) or use anAppCompatButton
instead – Lunenew Button(this, null, R.attr.buttonStyle);
doesn't work because it uses the same style defined with the attributebuttonStyle
but it is a Button and not anAppCompatButton
. It means that the implementations are different. Check the answer below. – Laden