我向名为 font 的文本视图添加了一个自定义属性。它会自动加载自定义字体。
示例 xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.egeniq.widget.TextView
android:layout_width="match_parent"
android:layout_height="44dp"
app:font="MyriadPro"
android:text="@string/login_welcome" />
</RelativeLayout>
自定义小部件在其构造函数中执行以下操作:
TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.TextView);
String customFont = styledAttrs.getString(font);
// snip. The error occurs here
R.styleable.TextView 声明如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="font" format="string" />
<!-- TextView -->
<declare-styleable name="TextView">
<attr name="font" />
</declare-styleable>
</resources>
当一切都按上述定义时,它可以工作。变量String customFont
设置为正确的名称 (MyriadPro)。
当尝试通过样式自动应用此值时,customFont 字符串为空。
样式声明如下:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.BicycleBuddy" parent="android:Theme.Light.NoTitleBar">
<item name="android:textViewStyle">@style/Widget.TextView</item>
</style>
<!-- Override defaults -->
<style name="Widget.TextView" parent="@android:style/Widget.TextView">
<item name="font">MyriadPro</item>
</style>
</resources>
主题包含在清单中:
<application
android:name=".Application"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.BicycleBuddy" >
</application>
<item name="font"></item>
没有给出错误。自定义小部件已加载并命中断点。不过就像上面说的。如果像这样使用,'customFont' 属性在阅读后为空。
堆栈的屏幕截图:第一个(customFont 不为空)是 XML 本身包含app:font=""
属性的位置。第二个,是它不包含这个属性的地方,但是应该从样式中加载它
View 元素不同的原因是因为它们只是 2 个不同的文本视图。具有完全相同的属性。只有1个包含app:font=""
,另一个不包含。断点按我预期的顺序依次击中 1 个。
如您所见,几乎一切都是平等的。甚至 styledAttrs 后面的 ID 也是一样的。然而,如果它没有在 XML 中明确声明字体属性,它就不会被加载。
我希望有人直接看到我缺少什么联系。但我确实意识到这是一个相当模糊的问题。
请注意 com.egeniq.* 是附加到我的项目的自定义库。styles.xml 在“主项目”中声明,而 attrs.xml 来自库项目