dazza5000
dazza5000

Reputation: 7628

How can we create a typeface from a downloadable font?

I have a helper method that does the following:

public CustomTypefaceSpan(Context context, String typefaceName) {
    mTypeface = sTypefaceCache.get(typefaceName);

    if (mTypeface == null) {
        mTypeface = Typeface.createFromAsset(context.getApplicationContext().getAssets(),
                String.format("fonts/%s", typefaceName));

        // Cache the loaded Typeface
        sTypefaceCache.put(typefaceName, mTypeface);
    }
}

After switching to downloadable fonts we get the following exception because there isn't a font available in the assets folder. How could we perform this action with a downloadable font? Thank you!

Caused by: java.lang.RuntimeException: Font asset not found fonts/OpenSans-Regular.ttf at android.graphics.Typeface.createFromAsset(Typeface.java:206) at com.woot.util.ui.CustomTypefaceSpan.(CustomTypefaceSpan.java:19) at com.woot.util.ui.ActivityUtil.setTitleCustomFont(ActivityUtil.java:20) at com.woot.storelocator.selectstorelanding.SelectStoreActivity.onCreate(SelectStoreActivity.java:40) at android.app.Activity.performCreate(Activity.java:6664) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)  at android.app.ActivityThread.-wrap12(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6077)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

Upvotes: 1

Views: 258

Answers (1)

mhdtouban
mhdtouban

Reputation: 881

The following sample code illustrates the overall Downloadable Fonts process:

 FontRequest request = new FontRequest("com.example.fontprovider.authority",
            "com.example.fontprovider", "my font", certs); 
    FontsContract.FontRequestCallback callback =
        new FontsContract.FontRequestCallback() { 
            @Override 
            public void onTypefaceRetrieved(Typeface typeface) {
                // Your code to use the font goes here 
                ... 
            } 

            @Override 
            public void onTypefaceRequestFailed(int reason) {
                // Your code to deal with the failure goes here 
                ... 
            } 
    }; 
FontsContract.requestFonts(context, request, callback , handler);

Upvotes: 1

Related Questions