修改Typeface.java和TextView.java这2个文件,实现此功能的Demo,测试有效。
1. Typeface.java:
public static Typeface defaultFromStyle(@Style int style) {
return mUserSetTf != null ? sDefaults_user[style] : sDefaults[style];
}
static {
final ArrayMap<String, Typeface> systemFontMap = new ArrayMap<>();
final ArrayMap<String, FontFamily[]> systemFallbackMap = new ArrayMap<>();
buildSystemFallback("/system/etc/fonts.xml", "/system/fonts/", systemFontMap,
systemFallbackMap);
sSystemFontMap = Collections.unmodifiableMap(systemFontMap);
sSystemFallbackMap = Collections.unmodifiableMap(systemFallbackMap);
setDefault(sSystemFontMap.get(DEFAULT_FAMILY));
// Set up defaults and typefaces exposed in public API
DEFAULT = create((String) null, 0);
DEFAULT_BOLD = create((String) null, Typeface.BOLD);
SANS_SERIF = create("sans-serif", 0);
SERIF = create("serif", 0);
MONOSPACE = create("monospace", 0);
sDefaults = new Typeface[] {
DEFAULT,
DEFAULT_BOLD,
create((String) null, Typeface.ITALIC),
create((String) null, Typeface.BOLD_ITALIC),
};
++setupDefaultFont();
}
public static Typeface mUserSetTf;
public static String mUserSetTfPath;
private static Typeface[] sDefaults_user;
static public void setupDefaultFont() {
String path = android.os.SystemProperties.get("persist.sys.usertf.path", "");
if (path != null && (new File(path)).exists()) {
mUserSetTfPath = path;
mUserSetTf = createFromFile(path);
sDefaults_user = new Typeface[] {
mUserSetTf,
mUserSetTf,
mUserSetTf,
mUserSetTf,
};
} else {
mUserSetTfPath = null;
mUserSetTf = null;
sDefaults_user = null;
}
}
2. TextView.java
private void setText(CharSequence text, BufferType type,
boolean notifyBefore, int oldlen) {
mTextSetFromXmlOrResourceId = false;
if ((Typeface.mUserSetTf != null && getTypeface() == null) ||
(Typeface.mUserSetTf != null
&& getTypeface() != null
&& !getTypeface().equals(Typeface.mUserSetTf)
)) {
setTypeface(Typeface.mUserSetTf, getTypeface() != null ? getTypeface().getStyle() : Typeface.NORMAL);
}
if (text == null) {
text = "";
}
// If suggestions are not enabled, remove the suggestion spans from the text
if (!isSuggestionsEnabled()) {
……
public void setTypeface(@Nullable Typeface tf, @Typeface.Style int style) {
if (style > 0) {
if (tf == null) {
tf = Typeface.defaultFromStyle(style);
} else {
if (Typeface.mUserSetTf != null && (tf == Typeface.DEFAULT || tf == Typeface.DEFAULT_BOLD)) {
tf = Typeface.create(Typeface.mUserSetTf, style);
} else {
tf = Typeface.create(tf, style);
}
}
setTypeface(tf);
// now compute what (if any) algorithmic styling is needed
int typefaceStyle = tf != null ? tf.getStyle() : 0;
int need = style & ~typefaceStyle;
mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
} else {
mTextPaint.setFakeBoldText(false);
mTextPaint.setTextSkewX(0);
setTypeface(tf);
}
}