简单实现自定义Android TextView字体

效果图:

在这里插入图片描述

如何做?

  • 引入自定义字体,如果Android工程里面没有assets文件夹,在Android视图下可以右键app,选择New -> Folder -> Assets Folder

在这里插入图片描述

右键assets文件夹,选择New -> Folder -> Font Resources Folder

在这里插入图片描述
到这里要注意了!需要改下fonts文件夹的路径,就是勾上Change Folder Location,填src/main/assets/fonts,不然会按照默认路径:src/main/res/font/ 建文件夹的。

在这里插入图片描述

最后将字体文件复制进fonts文件夹内,格式可以是ttf,也可以是otf

在这里插入图片描述

  • 代码使用:
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/包图小白体.ttf");
        mTvContent.setTypeface(tf);

也可以自定义TextView:

public class BTWhiteTextView extends AppCompatTextView {

    public BTWhiteTextView (Context context) {
        super(context);
        init(context);
    }

    public BTWhiteTextView (Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public BTWhiteTextView (Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context mContext) {
        Typeface tf = Typeface.createFromAsset(mContext.getAssets(), "fonts/包图小白体.ttf");
        setTypeface(tf);
    }

}

最后在xml文件上引用BTWhiteTextView即可:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <com.xz.android72test.ui.widget.BTWhiteTextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:textSize="38sp"
        android:textColor="#000"
        android:text="须知少时凌云志,\n曾许人间第一流。"/>
    
</android.support.constraint.ConstraintLayout>

非常感谢你能看到最后,如果能够帮助到你是我的荣幸。

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值