Unresolved reference: font in Android Studio

Viewed 767

I am trying to set a font to a text view in android studio but for some reasons, I cannot access the font directory.

I get Unresolved Reference: font

What I did

- Created a new directory by right clicking res > new > Android Resource Directory > Directory name : font > Resource type : font

- Placed my font in that directory, so the directory reads - res/font/myfont.ttf

- In my fragment I tried to access the font like this

var typeFace: Typeface? = ResourcesCompat.getFont(requireContext(), R.font.myfont.ttf)

Error shows Unresolved Reference: font

I tried to rebuild project but still not working.

3 Answers

Use:

typeFace: Typeface? = ResourcesCompat.getFont(requireContext(), R.font.myfont)

Do not add .ttfextension.

public static Typeface getFont (Context context, int id)

Returns a font Typeface associated with a particular resource ID.

Try with

typeFace: Typeface? = ResourcesCompat.getFont(requireContext(), R.font.myfont)

FYI - Read officials guideline about Fonts in XML

Android 8.0 (API level 26) introduces a new feature, Fonts in XML, which lets you use fonts as resources. You can add the font file in the res/font/ folder to bundle fonts as resources. These fonts are compiled in your R file and are automatically available in Android Studio. You can access the font resources with the help of a new resource type, font. For example, to access a font resource, use @font/myfont, or R.font.myfont.

NOTE

You can call custom font ttf/otf directly. Use createFromAsset

 val font = Typeface.createFromAsset(requireContext().assets,"font/myfont.ttf")

The problem was that:

  • "R" class imported was the framework resource "android.R"

  • I had to delete that and import My project "R" class "com.myproject.project.R"

And call like this

  • val typeFace: Typeface? = ResourcesCompat.getFont(requireContext(), R.font.poppings)

No error again.

Related