简体   繁体   中英

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?

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)

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM