Android:Lollipop 之前自定义按钮的背景颜色设置不正确

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

当我使用标准按钮时

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

风格:

<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>

主题:

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

一切正常,每个 api 级别 16+

都设置了背景颜色

但是当我使用自定义按钮时(用 kotlin 编写,需要自定义字体)

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)
}

}

背景颜色仅在 API21+ (Lollipop) 设备上设置。在棒棒糖之前的设备上,按钮保持标准的灰色。

为什么?

如果您正在使用 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.