Wednesday 31 August 2011

Android: referencing a custom view in an xml layout description

So you've created your own custom view called MyCustomView in a package named com.myproject.myviews, your custom view extends the View class (or one of its sub-classes) and it only has one constructor as follows:

public MyCustomView(Context context) {
 super(context);
 initialise();
}

Your custom view calls an initialise() method which you've defined to do all its initialisation. Next, you add this view to an xml layout definition as follows:

<view
  class="com.myproject.myviews.MyCustomView"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />

Now, when you run your app, it will crash failing to initialise the view. What you need to do to get over this is to add the following two constructors to your custom view:

public MyCustomView(Context context, AttributeSet attrs) {
  super(context, attrs);
  initialise();
}

public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  initialise();
}

These two constructors call the super constructors required for inflating a view from xml.

2 comments:

Anonymous said...

thanks - if I didn't find this I don't know how long I would have continued banging my head on the desk for....

Anonymous said...

Thank you! This was exactly my problem. :)