我可以更改Android自定义键盘的输出字体吗



我开发了一个android自定义键盘。我需要更改实际使用Unicode打印的输出文本的字体样式。

如何在不更改设备默认字体的情况下,在整个设备的任何位置更改键盘文本输出的字体样式?

字体也不在android设备中,所以我们必须从开发键盘的同一应用程序中对字体进行外部特权。

更改应用程序内部的字体样式。

创建一个名为的简单类

FontOverride

import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;
public final class FontsOverride {
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();
    }
    }
}

现在创建另一个类来覆盖名为的字体

应用

public final class Application extends android.app.Application {
    @Override
    public void onCreate() {
        super.onCreate();
        FontsOverride.setDefaultFont(this, "DEFAULT", "fonts/GeezEdit.ttf");
        FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/GeezEdit.ttf");
        /*FontsOverride.setDefaultFont(this, "MONOSPACE", "MyFontAsset2.ttf");
        FontsOverride.setDefaultFont(this, "SERIF", "MyFontAsset3.ttf");
        FontsOverride.setDefaultFont(this, "SANS_SERIF", "MyFontAsset4.ttf");*/
    }
}

现在将此字体添加到值文件夹的android样式文件中的样式中

<item name="android:typeface">monospace</item>

最后提到应用程序名称在android Manifest文件内的应用程序标签

android:name=".Application"

这将用于将用户提供的字体更改为android项目或应用程序。

最新更新