Android Studio – Define class that requires context and attributes in main activity



I am trying to use a custom class in my main activity.

DrawingCanvas drawingCanvas = new DrawingCanvas();

To define the class I have to pass it two arguments. This is my constructor.

public DrawingCanvas(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
}

I know I need to do something like below, but I am not sure what to pass for the attributes set.

DrawingCanvas drawingCanvas = new DrawingCanvas(this, );

Answer

I assume DrawingCanvas is extending from the View class or one that inherits from it.

In this case, it’s convenient to have the constructors similar to this:

    public DrawingCanvas(@NonNull Context context) {
        this(context, null);
    }

    public DrawingCanvas(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DrawingCanvas(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // more codeā€¦
    }

That way you can choose the most adequate one. As you can see, when there’s no AttributeSet, you can just pass null.

Now you would only need to do it like this:

DrawingCanvas drawingCanvas = new DrawingCanvas(this);


Source: stackoverflow