Android为TextView添加字体库和设置描边的方法
2020年02月01日
作者:佚名
一、使用系统自带的字体
开发Android的人大多都知道,Android里面对字体的支持少得可怜,默认情况下,TextView 的 typeface 属性支持 sans、serif和monospace 这三种字体,如果在没有指定字体的情况下,系统会使用 sans 作为文本显示的字体。但这三种字体只支持英文,也就是说只要你显示的文字是中文,无论你选择这三种字体中的哪一种,显示效果都是一样的。
1.在XML文件中设置
<!-- 使用默认的sans字体--> <TextView android:id="@+id/sans" android:text="Hello,World" android:textSize="20sp" android:typeface="sans" /> <!-- 使用默认的serifs字体--> <TextView android:id="@+id/serif" android:text="Hello,World" android:textSize="20sp" android:typeface="serif" /> <!-- 使用默认的monospace字体--> <TextView android:id="@+id/monospace" android:text="Hello,World" android:textSize="20sp" android:typeface="monospace" />
2.在Java代码中设置
第一步: 获取TextView实例
//获取textView实例 TextView textView = findViewById(R.id.textview);
第二步:设置字体
//设置serif字体 textView.setTypeface(Typeface.SERIF); //设置sans字体 textView.setTypeface(Typeface.SANS_SERIF); //设置monospace字体 textView.setTypeface(Typeface.MONOSPACE);
二、为TextView添加字体库
Android系统自带有对字体的设置,这些设置是对字体的显示方式的设置,比如加粗、倾斜、下划线、字号等,但是并没有提供对于字体类型的徐选择,比如设置成楷体、隶书或雅黑等。Android系统只固定默认一种字体类型,所以如果开发人员需要修改字体类型,那么就必须需自己引入字体库。
1.引入字体库的实现
第一步:在assets目录下新建fonts目录,并把ttf字体文件放到该目录下。
第二步:在Java代码中实现
//实例化TextView TextView textView = findViewById(R.id.textview); //得到AssetManager AssetManager mgr=getAssets(); //根据路径得到Typeface Typeface tf=Typeface.createFromAsset(mgr,"fonts/pocknum.ttf"); //设置字体 textView.setTypeface(tf);
2.引入字体库后的效果图
微信公众号搜索 “ 程序精选 ” ,选择关注!
精选程序员所需精品干货内容!