I am making a small app for Android, where I have a RelativeLayout, which amongst other things contains a custom ImageView. In my Java code I have this class:
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);
}
}
Then in my RelativeL开发者_运维问答ayout xml I have the following:
<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>
When I run my main class (not shown here) then my program crashes. If I omit the xml reference to ArrowImageView, then it does not crash.
Am I referring to my custom class te wrong way, or what is going on?
When extending the View widgets, if you plan to use them in XML layouts you need to also override the constructors that take the AttributeSet argument.
First don't extend ImageView but just View, unless there is something special about ImageView that you know and want to use.
Second, as Leffel said, you need to state attribute set like this
public ArrowImageView(Context context, AttributeSet set) {
super(context, set);
}
Also you may need to give some size to the custom view by setting witdh and height to something like 100dp. I am not sure what a custom View can "wrap" when there is no other views inside.
Thanks for the answers. I found a bug in the onPaint method itself which still made things crash. After implementing your suggestions and changing the onPaint into:
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.MAGENTA);
canvas.drawCircle(10,10,10,paint);
}
everything worked! Thank you very much for your help :-)
精彩评论