Android TextView 自定义字体设置
如何在Android中,对TextView设置自己喜欢的字体呢? 下面介绍 2 种方法:
第一种:代码中动态设置:
<!-- 这里没有设定字体,将在Java代码中设定-->
<TextView
android:id="@+id/custom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="36sp"
android:text="ABCDEF"/>
① 在Android中引入其他字体,首先要将字体文件保存在assets/fonts/目录下(字体格式.ttf):
②得到TextView控件对象 :
TextView textView =(TextView)findViewById(R.id.custom);
③将字体文件保存在assets/fonts/目录下,创建Typeface对象 :
Typeface typeFace =Typeface.createFromAsset(getAssets(),”fonts/itcblkad.ttf”);
④使用字体 :
textView.setTypeface(typeFace);
第二种:自定义TextView设置:
①建立MyApplication的类,用来设置字体:
package com.exam.mygitapplication.myapp;
import android.app.Application;
import android.graphics.Typeface;
/**
* Created by YuShuangPing on 2019/3/8.
*/
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/itcblkad.TTF");//下载的字体
}
public static MyApplication getInstance(){
return instance;
}
public Typeface getTypeface(){
return typeface;
}
public void setTypeface(Typeface typeface){
this.typeface=typeface;
}
}
②在AndroidManifest清单中初始化MyApplication:
<application
android:name=".myapp.MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
③自定义MyTextView:
/**
* Created by YuShuangPing on 2019/3/8.
*/
public class MyTextView extends TextView {
public MyTextView(Context context) {
super(context);
//设置字体
setTypeface(MyApplication.getInstance().getTypeface());
}
public MyTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
//设置字体
setTypeface(MyApplication.getInstance().getTypeface());
}
public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//设置字体
setTypeface(MyApplication.getInstance().getTypeface());
}
}
④准备好之后直接Xml中使用:
<com.exam.mygitapplication.view.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="36sp"
android:text="ABCDEF"/>
最后两种方式的效果如下:
总结:
1、第一种可以改变字体,但是不适合大范围使用,会出现视图展现卡顿现象
2、适合大范围使用,只是比第一种复杂
3、第一种适合一些静态展现,不需要经常刷新界面的地方,动态展示推荐第二种方案,比如Adapter布局当中