12

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 font style of my keyboard's text output anywhere throughout the device without having to change the device's default font?

The font is also not in android device, so we have to privide the font externally from the same application which is developing the keyboard.

1 Answer 1

5
+50

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

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

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.

1
  • 3
    this answer is working but i need to change the font outside the application. Dec 28, 2015 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.