自定义字体的TextView
2021-01-28 本文已影响0人
简秋默
在Android开发中,UI在设计界面时有时会用到一些特殊字体,这就要求我们能自定义一种可改变字体样式的TextView,这里记录一篇自定义的TextView,可实现要求。
其次在attrs.xml里面先定义自有的属性:
<!--自定义字体-->
<declare-styleable name="TypefaceTextView">
<attr name="typeface" format="string" />
</declare-styleable>
然后自定义TextView继续TextView。
package com.******;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import com.****.R;
public class TypefaceTextView extends AppCompatTextView {
public TypefaceTextView(@NonNull Context context) {
super(context);
}
public TypefaceTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initTypefaceTextView(context, attrs);
}
public TypefaceTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initTypefaceTextView(context, attrs);
}
private void initTypefaceTextView(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TypefaceTextView);
String type = typedArray.getString(R.styleable.TypefaceTextView_typeface);
if(null == type){
return;
}
Typeface typeface = null;
switch (type) {
case "Alibaba-PuHuiTi-Bold":
typeface = Typeface.createFromAsset(context.getAssets(), "Alibaba-PuHuiTi-Bold.ttf");
setTypeface(typeface);
break;
case "Alibaba-PuHuiTi-Regular":
typeface = Typeface.createFromAsset(context.getAssets(), "Alibaba-PuHuiTi-Regular.ttf");
setTypeface(typeface);
break;
default:
break;
}
if (typedArray != null) {
typedArray.recycle();
}
typeface = null;
}
}
最后使用时,如下即可
<com.xiding.aistush.widget.TypefaceTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:typeface="Alibaba-PuHuiTi-Bold"
android:textSize="20sp"
android:text="@string/appname"
android:textColor="@color/white"/>
<!-- Alibaba-PuHuiTi-Bold :assets下字体的名称 -->