我有一个自定义的TextView,基本上实现方式与这篇博客文章中的相同,它默认使用某种字体,但使用
textStyle
属性来设置普通、粗体或斜体风格的不同字体。
构造函数检查textStyle
并设置字体。
MyFontTextView.java
public MyFontTextView(Context context, AttributeSet attrs) {
int textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL);
switch (textStyle) {
case Typeface.BOLD: // bold
Typeface boldFont = Typeface.createFromAsset(Application.getContext().getAssets(), "fonts/boldFont.otf");
super.setTypeface(boldFont);
...
}
}
问题是,如果我在继承的 style
中设置了 textStyle
,它不会被检测到,getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL)
总是返回我的默认值 Typeface.NORMAL
:
<style name="TextView_MyInfo">
<item name="android:textStyle">bold</item>
<item name="android:textAllCaps">true</item>
</style>
myfragment.xml
<com.myapp.views.MyFontTextView
android:id="@+id/myinfo_name"
style="@style/TextView_MyInfo"
tools:text="John Smith" />
不设置粗体。
但是如果我直接在元素上设置textStyle
,像这样:
<com.myapp.views.MyFontTextView
android:id="@+id/myinfo_name"
android:textStyle="bold"
tools:text="John Smith" />
它确实检测到了,并且getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL)
返回的是Typeface.BOLD,这正如它应该的那样。我也知道它正确地加载了styles.xml
属性,因为它总是获取textAllCaps
属性以及其他一些属性。
我需要以不同于直接设置属性的方式访问在styles.xml
中设置的属性吗?
根据这个答案,如果我至少可以得到用style="@style/TextView_MyInfo"
设置的样式标签,我可以使用它来检查是否在那里定义了textStyle
。
其他信息:
- compileSdkVersion 23
- minSdkVersion 19
- targetSdkVersion 22