我正在开发一个支持 Jelly Beans 及以上版本的 Android 应用程序。我自己的风格定义为:
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
</style>
<style name="AppTheme.Child" parent="AppTheme">
<item name="colorButtonNormal">@color/login_button_enabled</item>
</style>
<style name="HomeButton" parent="Widget.AppCompat.Button">
<item name="android:background">@drawable/home_button</item>
</style>
drawable/home_button.xml 定义为:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="@dimen/button_inset_horizontal_material"
android:insetTop="@dimen/button_inset_vertical_material"
android:insetRight="@dimen/button_inset_horizontal_material"
android:insetBottom="@dimen/button_inset_vertical_material">
<shape android:shape="rectangle">
<corners android:radius="@dimen/control_corner_material" />
<solid android:color="?attr/colorButtonNormal" />
<padding android:left="@dimen/button_padding_horizontal_material"
android:top="@dimen/button_padding_vertical_material"
android:right="@dimen/button_padding_horizontal_material"
android:bottom="@dimen/button_padding_vertical_material" />
</shape>
</inset>
</item>
</selector>
这种风格在 Lollipop+ 中完美运行,但是对于 pre-lollipop Android,如果我添加 style="@style/home_button"它就会崩溃。 logcat 将错误显示为:
java.lang.RuntimeException: Unable to start activity ComponentInfo{my.domain.app/my.domain.app.MyActivity}: android.view.InflateException: Binary XML file line #46: Error inflating class Button
...
Caused by: android.view.InflateException: Binary XML file line #46: Error inflating class Button
...
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/home_button.xml from drawable resource ID #0x...
...
Caused by: java.lang.UnsupportedOperationException: Can't convert to color: type=0x2
如果我删除行 <solid android:color="?attr/colorButtonNormal" />
应用程序不会崩溃,但颜色不会呈现。 我想我的风格有问题,但我无法意识到是什么。我的 build.gradle 中的构建配置和库是:
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "xx.xxxx.xxx"
minSdkVersion 14
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
debug {
testCoverageEnabled true
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:design:22.2.1'
compile 'com.android.support:cardview-v7:22.2.1'
compile project(':xxxxx')
}
感谢您的帮助!
最佳答案
您没有做错任何事 - 可绘制对象的主题属性(在您的情况下为 ?attr/colorButtonNormal
)在 Lollipop 之前的设备上根本不受支持。 (参见 this Issue 作为引用)
因此,要么直接引用颜色,要么为您想要支持的每种可能的颜色创建一个 home_button.xml 并将它们添加到您稍后在 Activity 代码中设置的不同主题。
关于java - 对于预 Lollipop 设备使用 attr 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31715645/