Android custom view context is null.. how can that be?

1.9k Views Asked by At

I am working on a very simple custom view, my view simply extends view, and has a draw method

public class MyView extends View ;



public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    System.out.println("CONTEXT!!! "+context);
}

@Override
public void draw (Canvas canvas){
...
}

The XML definition is:

<com.mycode.MyView
     android:id="@+id/overlay"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
 />

Android properly tries to instantiate the class, and calls as expected the draw... unfortunately the in the draw method, the context is null. So I placed in the system.out.println in the constructor to see that the context is not null when instantiated... but that line never gets hit... So what is going on? Am I in some lifecycle that I am not understanding that Android could be calling draw before its finished creating the context? How the heck do I get Context to be anything but null in this case?

I don't understand how the view could be getting instantiated/inflated to the point of the draw method being called, but have no context.

Any help would be appreciated.

1

There are 1 best solutions below

3
On BEST ANSWER

View has 4 constructors (as of API 21). The framework is probably calling View(android.content.Context, android.util.AttributeSet, int) version of the constructor preventing you from seeing the Log statement.

I do not know how you are getting reference of the Context, but my bet is that you are setting something like this.context = context inside the constructor that is not being called. Use View.getContext() inside onDraw() instead.