• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

159
Views
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, );
about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error