开发Android应用程序时,我发现每次尝试在TextView上使用自定义字体时,我都会复制相同的行:
TextView textview = (TextView) findViewById(R.id.text);
textview.setTypeface(...)
显然,这是不必要的和重复的。 为什么不只是创建自定义视图? 还有,为什么不通过xml代码添加字体呢?
public class CustomTextView extends TextView {
private Context mContext;
private String mFont;
public CustomTextView(Context context) {
super(context, null);
mContext = context;
init();
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.CustomButtom,
0, 0);
try {
mFont = a.getString(R.styleable.CustomButtom_font);
} finally {
a.recycle();
}
init();
}
private void init() {
if (mFont != null) {
setTypeface(FontsUtils.get(mFont));
}
}
}
我们只需要从TextView扩展并从属性集读取在其可样式化资源上声明的字体字符串即可。 只需创建attrs.xml(或使用现有的attrs.xml)并添加以下内容:
<declare-styleable name="CustomTextview">
<attr name="font" format="string" />
</declare-styleable>
现在,您可以像这样在xml布局上声明:
<LinearLayout
android:id="@+id/comments"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.parkuik.android.ui.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/no_comments" />
</LinearLayout>
参考: Javier Manzano博客博客中来自我们JCG合作伙伴 Javier Manzano的具有自定义字体的Android TextView 。
翻译自: https://www.javacodegeeks.com/2013/01/android-textview-with-custom-fonts.html