0

I am implementing custom view in Android. I was always creating it like this e.g:

RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.view1);
CustomView customView = new CustomView(relativeLayout.getContext());
relativeLayout.addView(customView);

This is working fine. But when I tried something different:

CustomView customView = (CustomView) findViewById(R.id.customView);

in xml it's like this:

 <com.my.package.CustomView
       android:id="@+id/customView"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>

I've got the error: android.view.InflateException: Binary XML file line #14: Error inflating class

My custom view extends RelativeLayout and this is the only constructor:

public CustomView(Context c){
    super(c);
    //adding some html to the webview here
}

Am I missing something?

Cœur
  • 34,719
  • 24
  • 185
  • 251
shurrok
  • 685
  • 2
  • 13
  • 40

1 Answers1

2

When you use your custom view from XML, the single argument constructor will not be used. Rather two/three argument constructors will be used.

You should add other constructors as well:

public CustomView(Context context) {
    super(context);
}

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

public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}
Nabin Bhandari
  • 15,064
  • 6
  • 44
  • 55