一、在Android开发中会遇到系统提供的字体并不能满足自己对字体的设计需要,这就需要引进外部字体库了。下面简述一下如何引入外部字体库。
1>在自己工程文件目录下新建一个assets文件夹,在assets文件夹里面新建一个font文件夹。
具体路径如下图:
2>然后将字体包如同图片文件一样放到font这个文件夹里面。
3>利用TypeFace实现单个TextView的字体替换。
具体代码如下:
tv_Text=(TextView)findViewById(R.id.tv_text);
typeface=Typeface.createFromAsset(getAssets(),"font/main.ttf");
tv_Text.setTypeface(typeface);
4>有一种全局替换字体的方式如下:
(1)、新建一个Application的类,类名自定义;
(2)、在AndroidMainfest中声明这个类:
如下代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mainexample">
<application
android:name=".FontApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".FontActivity" />
<activity android:name=".circlemove"></activity>
</application>
</manifest>
android:name=".FontApplication"就是声明的这个类。
(3)、在这个自定义的类中onCreate里面写下如下代码:
FontApplication.java
package com.example.mainexample;
import android.app.Application;
import android.content.Context;
import android.graphics.Typeface;
import java.lang.reflect.Field;
/**
* Created by 尽途 on 2017/5/24.
*/
public class FontApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
setDefaultFont(this,"MONOSPACE","font/main.ttf");//更换字体的主要语句
}
public static void setDefaultFont(Context context,
String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(),
fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
protected static void replaceFont(String staticTypefaceFieldName,
final Typeface newTypeface) {
try {
final Field staticField = Typeface.class
.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
二、程序开发过程里面会遇到想让一句话竖直排列,这应该如何办呢?
其实这个问题也很好解决。在程序中控制ems为1就可以了。
1>在html中的解决方案:
<TextView
android:id="@+id/tv_text"
android:text="你好"
android:ems="1"
android:textSize="56sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
2>在java中的结局方案:
tv_Text=(TextView)findViewById(R.id.tv_text);
tv_Text.setMyEms(1);