Android自己设置字体–自己设置TextView(可扩展不同ttf字体)

作者 : 开心源码 本文共1563个字,预计阅读时间需要4分钟 发布时间: 2022-05-12 共253人阅读

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. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Android自己设置字体–自己设置TextView(可扩展不同ttf字体)

发表回复