Java 在Android上使用自定义字体

Java 在Android上使用自定义字体,java,android,fonts,Java,Android,Fonts,我正在尝试加载自定义字体,如下所示: private Paint customFont18; customFont18 = new Paint(); customFont18.setTextSize(18); Typeface fontFace = Typeface.createFromAsset(getAssets(), "FONT.TTF"); customFont18.setTypeface(fontFace); getAssets失败,但出现以下情况: -The method get

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

private Paint customFont18;
customFont18 = new Paint();
customFont18.setTextSize(18);
Typeface fontFace = Typeface.createFromAsset(getAssets(), "FONT.TTF"); 
customFont18.setTypeface(fontFace);
getAssets失败,但出现以下情况:

-The method getAssets() is undefined for the type MyClass
-assetManager cannot be resolved to a variable
我有什么问题?我见过几个这样的例子,但在我的例子中没有一个是有效的。 提前感谢。

getAssets()
是一种上下文方法。如果类不是活动,则需要向其中传递上下文,然后调用
getAssets()

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

尝试如下更改:

Typeface fontFace = Typeface.createFromAsset(getAssets(), "fonts/FONT.TTF");
使用简单的第三方库为您的
TextView
设置各种自定义字体。通过使用此库,您不必担心下载字体并将其添加到assets/fonts文件夹中。还有关于字体对象的创建

简单地说:

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

此库还提供多种字体。

否,必须是活动才能工作?否,不一定是活动才能工作。您的FONT.TTF文件位于项目的何处?字体位于“资产”文件夹中