Android TextView 自定义字体设置(华文行楷TTF)

如何在Android中,对TextView设置自己喜欢的字体呢?
原文转自:https://blog.csdn.net/shiyangkai/article/details/70257004
本文提供一个ttf 华文行楷下载的地址:https://pan.baidu.com/s/1UW6yw6IxIEIUahJY88hPdQ

下面介绍 2 种方法:

1、代码中动态设置:

  <!--  这里没有设定字体,将在Java代码中设定-->
  <TextView   Android:id="@+id/custom"
                     Android:text="Hello,World"
                     Android:textSize="20sp" />

 ① 在Android中引入其他字体,首先要将字体文件保存在assets/fonts/目录下(字体格式.ttf)

 ②//得到TextView控件对象
    TextView textView =(TextView)findViewById(R.id.custom);

  ③//将字体文件保存在assets/fonts/目录下,创建Typeface对象
  Typeface typeFace =Typeface.createFromAsset(getAssets(),”fonts/HandmadeTypewriter.ttf”);

  ④//使用字体
  textView.setTypeface(typeFace);

2、自定义TextView设置:

 ①建立MyApplication的类,用来设置字体

import android.app.Application;
import android.graphics.Typeface;

public class MyApplication extends Application {
private Typeface typeface;
private static MyApplication instance;

@Override
public void onCreate() {
    super.onCreate();
    instance = (MyApplication) getApplicationContext();
    typeface = Typeface.createFromAsset(instance.getAssets(), "fonts/zfkt.TTF");//下载的字体
}

public static  MyApplication getInstace() {
    return instance;
}

public Typeface getTypeface() {
    return typeface;
}

public void setTypeface(Typeface typeface) {
    this.typeface = typeface;
}

}

 ②在AndroidManifest清单中初始化MyApplication
<application
        android:name=".MyApplication.MyApplication" //初始化 MyApplication
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:icon">

      ③建立MyTextView

public class MyTextView extends TextView {
    public MyTextView(Context context) {
        super(context);
        //设置字体
        setTypeface(MyApplication.getInstace().getTypeface());
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //设置字体
        setTypeface(MyApplication.getInstace().getTypeface());
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //设置字体
        setTypeface(MyApplication.getInstace().getTypeface());
    }

}

      ④准备好之后直接Xml中使用

<com.ahbcd.app.fctms.utils.MyTextView        
            android:layout_width="@dimen/dp_60"
            android:layout_height="@dimen/dp_60"
            android:text="显示字体" />



总结:

1、第一种可以改变字体,但是不适合大范围使用,会出现视图展现卡顿现象

2、适合大范围使用,只是比第一种复杂

3、第一种适合一些静态展现,不需要经常刷新界面的地方,动态展示推荐第二种方案,比如Adapter布局当中

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值