malcoauri
malcoauri

Reputation: 12199

How to add my custom View to layout in xml?

There is the following xml:

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

    <com.ulnda.calendarapplication.MyCalendarView
        android:id="@+id/calendarView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

MyCalendarView:

public class MyCalendarView extends CalendarView {

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

    @Override
    public void setOnClickListener(OnClickListener listener) {
//      View v;
//      v.setOn

    }

    @Override
    public boolean performClick() {
        Log.e("event", "perform_click");
        return true;
    }
}

All is good, but when I'm trying to execute this application I'll have got the following message:

10-19 12:59:30.037: E/AndroidRuntime(30968): FATAL EXCEPTION: main
10-19 12:59:30.037: E/AndroidRuntime(30968): android.view.InflateException: Binary XML file line #7: Error inflating class com.ulnda.calendarapplication.MyCalendarView

How can I fix it?

Upvotes: 3

Views: 226

Answers (2)

Tobias Ritzau
Tobias Ritzau

Reputation: 3327

You need to implement some constructors for this to work. View has the following:

  • View(Context context)
  • [View(Context context, AttributeSet attrs)](http://developer.android.com/reference/android/view/View.html#View(android.content.Context, android.util.AttributeSet))
  • [View(Context context, AttributeSet attrs, int defStyle)](http://developer.android.com/reference/android/view/View.html#View(android.content.Context, android.util.AttributeSet, int))

The second and third are used for XML inflation. You need to implement the constructor for your view class that corresponds to the second, and possibly the third. That is, implement:

  • MyCalendar(Context context, AttributeSet attrs)

And add the following if you need (probably not):

  • MyCalendar(Context context, AttributeSet attrs, int defStyle)

Upvotes: 2

Lawrence Choy
Lawrence Choy

Reputation: 6108

Try to add these constructors too

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

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

Upvotes: 2

Related Questions