Johann
Johann

Reputation: 29877

Inflating a custom control in Android

In my activity I have a custom made control. In onCreate I inflate the activity's view as normal with:

setContentView(R.layout.image_viewer);

Here is my xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <MyCustomImageView
    android:id="@+id/tivImage"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

</LinearLayout>

And here is a reduced piece of code for MyCustomTextView:

 public class MyCustomImageView extends ImageView
 {
  Context context;

  public MyCustomImageView(Context context)
  {
    super(context);
    sharedConstructing(context);
  }

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

The exception that gets generated reads:

android.view.InflateException: Binary XML file line #7: Error inflating class MyCustomImageView

Upvotes: 0

Views: 577

Answers (2)

minipif
minipif

Reputation: 4876

You have to create constructors calling the superclass constructors, because they will be called by the inflater:

public class MyView extends View {

    public MyView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public MyView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

}

And you have to put the full package name in your XML:

<com.mypackagename.MyView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

Upvotes: 0

Zoubiock
Zoubiock

Reputation: 1165

you need to add the package name:

 <com.my.package.MyCustomTextView
    android:id="@+id/tivImage"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

Upvotes: 4

Related Questions