具有自定义字体的Android TextView

开发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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值