Search code examples
androidandroid-custom-view

Android: Background color on custom button not set correctly pre Lollipop


When I use a standard button

<Button
    android:id="@+id/btnLogin"
    style="@style/LoginButtonsStyle"
    android:text="@string/login.anmelden"
    android:theme="@style/CrGreenButton"/>

Style:

<style name="LoginButtonsStyle">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">@dimen/login_btn_height</item>
    <item name="android:textAllCaps">false</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:layout_marginBottom">@dimen/login_buttons_bottom_margin</item>
</style>

Theme:

<style name="CrGreenButton">
    <item name="colorButtonNormal">@color/CrGreen</item>
    <item name="android:colorBackground">@color/CrGreen</item>
    <item name="android:background">@color/CrGreen</item>
</style>

everything works fine and the background color gets set on each api level 16+

But when I use my custom Button (written in kotlin, needed for a custom font)

open class CheckrobinButton : Button {

val fontPath = "fonts/CoreSansG55.otf"

constructor(context: Context) : super(context) {
    init()
}

constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
    init()
}

constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr) {
    init()
}

constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes){
    init()
}

private fun init() {
    typeface = Typeface.createFromAsset(context.assets, fontPath)
}

}

the backgroundcolor is only set on API21+ (Lollipop) devices. On pre lollipop devices, the button stays in the standard grey color.

Why?


Solution

  • If you are using AppCompat, you need to extend AppCompatButton, rather than Button if you want to use the custom formatting and coloring prior to Lollipop with a custom class, as explained in the Android Support Library 22.1 blog post.