【发布时间】:2017-08-18 07:35:12
【问题描述】:
我有什么:
- 我有一个继承
AppCompatTextView的自定义类。 - 我在
attires.xml中定义了一个自定义属性textformat和 我正在传递我需要从 xml 设置的字体
样式文件
<style name="HeaderFilterName">
<item name="android:src">@drawable/back_button</item>
<item name="android:text">@string/str_filter_edit</item>
<item name="android:gravity">center</item>
<item name="android:textSize">@dimen/Header_Filter_Name_Text_size</item>
<item name="android:layout_weight">1</item>
</style>
XML
<customViews.CustomTftTextView
android:id="@+id/txtScreenNameId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:textformat="fonts/sf_san_fransisco.ttf"
style="@style/HeaderFilterName"/>
attr.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="customfont">
<attr name="textformat" format="string"/>
</declare-styleable>
</resources>
CustomTftTextView.java
public class CustomTftTextView extends AppCompatTextView {
private String text;
public CustomTftTextView(final Context context) {
this(context, null);
Initialize(text,context);
}
public CustomTftTextView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
text = context.getResources().obtainAttributes(attrs, R.styleable.customfont).getString(R.styleable.customfont_textformat);
Initialize(text,context);
}
public CustomTftTextView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
text = context.getResources().obtainAttributes(attrs, R.styleable.customfont).getString(R.styleable.customfont_textformat);
Initialize(text,context);
}
private void Initialize(String format, Context context) {
Typeface mTypeface;
if (format != null)
{
mTypeface = Typeface.createFromAsset(context.getAssets(), format);
}
else
{
mTypeface = Typeface.createFromAsset(context.getAssets(), "fonts/sf_san_fransisco.ttf");
}
setTypeface(mTypeface, Typeface.NORMAL);
setLineSpacing(0.0f, 1.4f);
}
}
虽然上面的代码完美运行,但如果我将 app:textformat 移动到 style 文件中,字体未设置。
<style name="HeaderFilterName">
<item name="android:src">@drawable/back_button</item>
<item name="android:text">@string/str_filter_edit</item>
<item name="textformat">@string/custom_font_medium </item>
<item name="android:gravity">center</item>
<item name="android:textSize">@dimen/Header_Filter_Name_Text_size</item>
<item name="android:layout_weight">1</item>
</style>
strings.xml
<string name="custom_font_medium">fonts/sf_san_fransisco.ttf</string>
如何正确实现这一目标
【问题讨论】:
标签: java android xml android-styles