在android上的自定义视图

时间:2012-09-03 02:43:22

标签: android view custom-component

我创建了自定义视图MyView

package com.example;

public class MyView extends View {

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

并在布局xml中使用它:

<com.example.MyView android:id="@+id/imageView"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent">
</com.example.MyView>

它抛出错误:

09-02 16:43:07.114: ERROR/AndroidRuntime(1387): FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to start activity 
        ComponentInfo{com.example/com.example.MyActivity}: android.view.InflateException: Binary XML file line #13:
           Error inflating class com.example.MyView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
        at android.app.ActivityThread.access$1500(ActivityThread.java:117)

如何解决?

1 个答案:

答案 0 :(得分:2)

您应该尝试为其工作定义另一个构造函数。

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