Forced Close after adding custom ImageView

2019-08-27 01:23发布

问题:

I'm trying to add a custom ImageView to my main.xml, but if I start the program it closes with a forced close.

XML:

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

     <test.testpkg.CustomImageView
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:layout_gravity="center_vertical"
          android:src="@drawable/bg"/>

</LinearLayout>

Java:

package test.testpkg;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.widget.ImageView;

public class CustomImageView extends ImageView {

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

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }
}

Also if I start the program in Debugger after the FC I only get this: link text

回答1:

Debugger is useless if you haven't attached the source code of Android. Moreover... it's more useful to provide the logcat output. Anyway, I think you are missing one of the constructors. Try this:

public class CustomImageView extends ImageView {

 public CustomImageView(Context context) {
  super(context);
  // TODO Auto-generated constructor stub
 }

 public CustomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
 }
 // rest of your code....