当我使用标准按钮时
<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) 设备上设置。在 Lollipop 之前的设备上,按钮保持标准的灰色。
为什么?
最佳答案
如果您使用 AppCompat , 你需要扩展 AppCompatButton , 而不是 Button
如果您想在 Lollipop 之前使用自定义格式和颜色与自定义类,如 Android Support Library 22.1 blog post 中所述.
关于Android:Lollipop 之前自定义按钮上的背景颜色设置不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36985988/