Search code examples
javaandroidandroid-contextandroid-typefaceandroid-custom-drawable

Acquire Context in custom Drawable class


I have tried to create a custom class in order to implement a text as drawable but I am unable to set Typeface to Paint. Below is the code implementation of the custom class (i.e. TextDrawable).

Here I want to get the context of Application to call the method getAssets(), but here I'm unable to call the method getContext().

public class TextDrawable extends Drawable {
    private final String text;
    private final Paint paint;

    public TextDrawable(String text) {
        this.text = text;
        this.paint = new Paint();
        paint.setColor(Color.GRAY);
        paint.setTextSize(35f);
        //paint.setTypeface(Typeface.createFromAsset(**getContext().getAssets()**, "fonts/Montserrat-Regular.otf"));
        paint.setAntiAlias(true);
        paint.setTextAlign(Paint.Align.RIGHT);
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.drawText(text, 0, 10, paint);
    }

    @Override
    public void setAlpha(int alpha) {
        paint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        paint.setColorFilter(cf);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }
}

Solution

  • I am not able to get getContext().getAssets() in this class.

    You have to pass a Context object as a parameter to your class's constructor:

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