Can I change the output font of an Android custom keyboard?

前端 未结 1 1394
逝去的感伤
逝去的感伤 2021-01-02 01:46

I have developed an android custom keyboard. I need to change the font style of my output text which are actually printed using the unicodes.

How can I change the f

1条回答
  •  长发绾君心
    2021-01-02 02:15

    changing the font style inside the application.

    create a simple class named

    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();
        }
        }
    }
    

    now create another class to override the fonts named

    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");*/
        }
    }
    

    now add this typeface to style in android style file at values folder

    monospace
    

    At last mention the Application name at android Manifest file inside application tag

    android:name=".Application"
    

    This will work to change the user provided font to the android project or application.

    0 讨论(0)
提交回复
热议问题