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

标签 android android-custom-view

当我使用标准按钮时

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

相关文章:

java - 获取所有应用在android上的运行时间

java - Android用2种颜色画圆(饼图)

java - Android 用图标构建迷你抽屉导航

android - 如何在 Android 应用程序中使用 UI 工具包 (PSD)

android - 帮助传递 ArrayList 和 parcelable Activity

android - 将 STL 链接到独立的 Android NDK 可执行文件

android - 如何在 Android 中创建圆形电话屏幕?

java - Android 中的 drawRoundRect 不工作

android - 让用户能够与屏幕上的 "ball"交互?

java - 如何根据用户在 Android 中输入的国家/地区访问或获取 ISO3 国家/地区代码