Android自定义字体--自定义TextView(可扩展不同ttf字体)

1.最简单直接的方式设置字体

(1)-初始化控件,拿到该控件的对象,设置字体

textView.setTypeface( Typeface.createFromAsset(this.getAssets(), "CodeBold.ttf"));

这种方式只适用于单个,少数字体需要改变样式。如果UI中每一行的字体样式都不一样呢?例如


ttf 字体

2.通过自定义TextView来设置字体

如下调用

<com.***.***.view.TypefaceTextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textSize="@dimen/font_12sp"
  app:typeface="@string/universal_text_typeface" />

在values下的strings中设置name

  <string name="universal_text_typeface">PingFangLight</string>

接下来 在values下创建一个attrs.xml文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TypefaceTextView">
        <attr name="typeface" format="string" />
    </declare-styleable>
</resources>

之后就是自定义TextView

public class TypefaceTextView extends android.support.v7.widget.AppCompatTextView {

    public TypefaceTextView(Context context) {
        this(context, null);
    }

    public TypefaceTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TypefaceTextView(Context context, 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 "PingFangLight":
                typeface = Typeface.createFromAsset(context.getAssets(), "PingFangLight.ttf");
                setTypeface(typeface);
                break;
            case "systemDefault":
                setTypeface(Typeface.DEFAULT);
                break;
        }
        if (typedArray != null) {
            typedArray.recycle();
        }
        typeface = null;
    }
}

这样就可以在布局中,设置不同的字体了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AGI阅读 16,009评论 3 119
  • 【Android 自定义View】 [TOC] 自定义View基础 接触到一个类,你不太了解他,如果贸然翻阅源码只...
    Rtia阅读 3,994评论 1 14
  • 青玉案 (宋)贺铸 凌波不过横塘路,但目送、芳尘去。锦瑟华年谁与度?月桥花院,琐窗朱户,只有春知处。 飞云冉冉蘅皋...
    婴城愚子阅读 609评论 0 5
  • 高估别人,看低自己。 所谓优越感,一种故意的姿态。 而我卑微到尘埃里。 当和一些能力差不多的人一起时,我很开...
    ca3c阅读 1,148评论 0 0
  • 昨天婆婆去马兰西亚旅游了,后天老妈和小舅妈也要出去旅游五天,亲爱的妈妈怕我晚上带两娃睡觉会疯,最后决定把辰宝...
    coca_gao阅读 82评论 0 1