user5366495
user5366495

Reputation:

I'm getting a NoSuchMethodError when setting a font on a TextView programically with the new font feature

From this official example https://developer.android.com/preview/features/working-with-fonts.html I'm trying to set a custom font for a TextView which works when set in XML/layout but not when setting it programmatically I get the following error:

java.lang.NoSuchMethodError: No virtual method getFont(I)Landroid/graphics/Typeface; in class Landroid/content/res/Resources; or its super classes (declaration of 'android.content.res.Resources' appears in /system/framework/framework.jar)

This is how I'm doing it by code:

    Typeface typeface = getResources().getFont(R.font.morganbold);
    providerTxv.setTypeface(typeface);

Is this a bug or I'm I doing something wrong?

I'm using Android Studio Canary 9 with Gradle version: gradle:3.0.0-alpha9 with these support depedencies:

'com.android.support:design:26.0.0'
'com.android.support:appcompat-v7:26.0.0'

Upvotes: 2

Views: 3254

Answers (2)

Maxence Barroy
Maxence Barroy

Reputation: 151

You must use

Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);

See docs

Upvotes: 12

Rajasekhar
Rajasekhar

Reputation: 2355

Find the solution (getFont() will work from Android 'O'(26.0.0-beta1) version. So we have to move the below solution):

  1. Put font.ttf/otf in assets folder

    Typeface light = Typeface.createFromAsset(getAssets(), "font.ttf");
    
  2. Set TypeFace in your view

     YourView.setTypeFace(light);
    

Please refer the link https://developer.android.com/reference/android/support/v4/content/res/ResourcesCompat.html#getFont(android.content.Context,int)

Upvotes: 0

Related Questions