Java 在自定义可绘制类中获取上下文

Java 在自定义可绘制类中获取上下文,java,android,android-context,android-typeface,android-custom-drawable,Java,Android,Android Context,Android Typeface,Android Custom Drawable,我试图创建一个自定义类来实现可绘制的文本,但无法将字体设置为绘制。 下面是自定义类的代码实现(即TextDrawable) 这里我想获取应用程序的上下文来调用方法getAssets(),但是这里我无法调用方法getContext() 我无法在此类中获取getContext().getAssets() 必须将上下文对象作为参数传递给类的构造函数: public class TextDrawable extends Drawable { ... publi

我试图创建一个自定义类来实现可绘制的文本,但无法将
字体设置为
绘制。
下面是自定义类的代码实现(即
TextDrawable

这里我想获取应用程序的上下文来调用方法
getAssets()
,但是这里我无法调用方法
getContext()


我无法在此类中获取getContext().getAssets()

必须将
上下文
对象作为参数传递给类的构造函数:


    public class TextDrawable extends Drawable {
        ...

        public TextDrawable(Context context, String text) {
            paint.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/Montserrat-Regular.otf"));
            ...
        }
        ...
    }

可绘制对象没有上下文。正如@azizbekian和@Mike M所建议的,你有两个选择

在构造函数中传递上下文 注意每次使用此绘图工具时,这种方法都会创建一个新的字体实例,这通常是一种不好的做法,也会直接影响性能

在构造函数中传递字体 这种方法更好,因为您可以对多个对象使用一个字体实例,这些对象与此绘图相关或不相关

扩展后一种方法,您可以创建一个静态字体提供者,如下所示。这样可以确保您始终只有一个字体实例

字体提供者
公共类字体提供程序
{
private static Map TYPEFACE_Map=new HashMap();
公共静态字体getTypeFaceForFont(上下文上下文,字符串fontFile)
{

如果(fontFile.length(),请确保取消注释代码行,如果这是有意的,请尝试使用联机工具将otf文件转换为ttf。您到底遇到了什么问题?您好,@IsmailIqbal comment是有意的,文件格式没有问题。我无法获取getContext().getAssets()在这个类中,我无法获取getContext().getAssets()在这个类中@MikeM。请参考这个,并检查评分最高的答案。它应该是
Typeface#createFromAsset(AssetManager mgr,字符串路径)
好的,如果我在应用程序类级别创建一个静态上下文,然后在这里使用该上下文如何。如果这样做有任何缺点。应用程序中的静态上下文是“不推荐、首选”方法。每个人都使用它,但没有人推荐它。所以,是的,你可以,只是不要告诉任何人我建议了它!>:)

    public class TextDrawable extends Drawable {
        ...

        public TextDrawable(Context context, String text) {
            paint.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/Montserrat-Regular.otf"));
            ...
        }
        ...
    }
public TextDrawable(Context context, String text) {
    paint.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/Montserrat-Regular.otf"));
    ...
}
public TextDrawable(String text, Typeface typeface) {
    paint.setTypeface(typeface);
    ...
}
public class TypefaceProvider
{
    private static Map<String, Typeface> TYPEFACE_MAP = new HashMap<>();

    public static Typeface getTypeFaceForFont(Context context, String fontFile)
    {
        if (fontFile.length() <= 0) throw new InvalidParameterException("Font filename cannot be null or empty");
        if (!TYPEFACE_MAP.containsKey(fontFile))
        {
            try
            {
                Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/"+fontFile);
                TYPEFACE_MAP.put(fontFile, typeface);
            }
            catch (Exception e)
            {
                throw new RuntimeException(String.format("Font file not found.\nMake sure that %s exists under \"assets/fonts/\" folder", fontFile));
            }
        }

        return TYPEFACE_MAP.get(fontFile);
    }
}