我可以为安卓自定义键盘更改输出字体吗?

12
我已经开发了一个Android自定义键盘。我需要更改输出文本的字体样式,这些文本实际上是使用Unicode打印的。
如何在整个设备上更改键盘文本输出的字体样式,而无需更改设备的默认字体?
该字体也不在Android设备中,所以我们必须从开发键盘的同一应用程序外部提供该字体。
1个回答

5
修改应用程序中的字体样式。
创建一个名为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();
    }
    }
}

现在创建另一个类来覆盖名为“Application”的字体。
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");*/
    }
}

现在将这种字体添加到位于values文件夹中的Android样式文件中。
<item name="android:typeface">monospace</item>

最后,在Android Manifest文件的应用程序标签中提到应用程序名称。
android:name=".Application"

这将适用于更改用户提供的字体到Android项目或应用程序中。


3
这个答案可以使用,但我需要改变应用程序之外的字体。 - Ankush Bist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接