自定义ImageView导致程序崩溃

5

我正在为Android制作一个小应用程序,其中包含RelativeLayout,其中包括自定义的ImageView等内容。在我的Java代码中,我有这个类:

package com.example.android.helloactivity;


class ArrowImageView extends ImageView {
    public ArrowImageView(Context context) {
        super(context);
    }
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(10,10,10,null);
    }
}

然后在我的RelativeLayout xml文件中,我有以下内容:

<RelativeLayout android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:background="#FFF"
            xmlns:android="http://schemas.android.com/apk/res/android">
    <Button ...... />
    <TextView ......./>

    <com.example.android.helloactivity.ArrowImageView
        android:id="@+id/hello_activity_bearingarrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

当我运行我的主类(此处未显示)时,我的程序崩溃。如果我省略对ArrowImageView的xml引用,则不会崩溃。
我是在错误地引用自定义类,还是出了什么问题?

我能够回答你的问题,但是以后参考起见,你应该始终包括你正在解决故障的崩溃的堆栈跟踪。 - LeffelMania
3个回答

10

在扩展View小部件时,如果您计划在XML布局中使用它们,您需要覆盖接受AttributeSet参数的构造函数。


4

首先,除非您知道并想要使用ImageView的某些特殊功能,否则不要扩展ImageView而是扩展View。

其次,如Leffel所说,您需要像这样声明属性集

public ArrowImageView(Context context, AttributeSet set) {         
 super(context, set);     
} 

同时,您可能需要通过将宽度和高度设置为100dp之类的值来为自定义视图提供一些大小。当没有其他视图时,我不确定自定义视图可以“包裹”什么。


0
感谢您的回答。我发现onPaint方法本身存在一个错误,这仍然会导致程序崩溃。在实施了您的建议并将onPaint更改为以下内容后:
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint paint = new Paint();
    paint.setColor(Color.MAGENTA);
    canvas.drawCircle(10,10,10,paint);
}

一切都正常运作!非常感谢您的帮助 :-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接