在Android上使用自定义字体

kar*_*e23 2 java fonts android

我正在尝试加载自定义字体,如下所示:

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

getAssets失败了,这个:

-The method getAssets() is undefined for the type MyClass
-assetManager cannot be resolved to a variable
Run Code Online (Sandbox Code Playgroud)

我的问题是什么?我见过几个这样的例子,但在我的情况下都没有.提前致谢.

Blu*_*mer 11

getAssets()是一种Context的方法.如果您的类不是活动,则需要将上下文传递给它,然后调用getAssets()它.

public myClass(Context myContext) {
    Typeface typeface = Typeface.createFromAsset(myContext.getAssets(), "FONT.TTF");
    ...
}
Run Code Online (Sandbox Code Playgroud)