karse23
karse23

Reputation: 4115

Using custom fonts on Android

I'm trying to load a custom font as follows:

private Paint customFont18;
customFont18 = new Paint();
customFont18.setTextSize(18);
Typeface fontFace = Typeface.createFromAsset(getAssets(), "FONT.TTF"); 
customFont18.setTypeface(fontFace);

The getAssets fails, thows this:

-The method getAssets() is undefined for the type MyClass
-assetManager cannot be resolved to a variable

What is my problem? I've seen several examples like this but none works in my case. Thanks in advance.

Upvotes: 2

Views: 4717

Answers (3)

Blumer
Blumer

Reputation: 5035

getAssets() is a method of Context. If your class is not an activity, you'll need to pass a context into it and then call getAssets() on that.

public myClass(Context myContext) {
    Typeface typeface = Typeface.createFromAsset(myContext.getAssets(), "FONT.TTF");
    ...
}

Upvotes: 11

Vijay Vankhede
Vijay Vankhede

Reputation: 3058

Use simple EasyFonts third party library to set variety of custom font to your TextView. By using this library you should not have to worry about downloading and adding fonts into the assets/fonts folder. Also about Typeface object creation.

Simply:

TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(EasyFonts.robotoThin(this));

This library also provides variety of font faces.

Upvotes: 0

Ommy
Ommy

Reputation: 1

Try changing like this:

Typeface fontFace = Typeface.createFromAsset(getAssets(), "fonts/FONT.TTF");

Upvotes: 0

Related Questions