在画布上绘制时出现空指针异常

时间:2013-10-31 10:31:22

标签: android xml canvas android-custom-view

我创建了一个自定义视图,当您沿着屏幕拖动手指时绘制线条然后我在xml布局中添加视图但是当我尝试在我添加的视图上绘制一些内容时{ {1}}布局,它为我提供了xml例外

自定义视图就像这样

nullpointer

在主要活动中添加布局

public class page extends View  
{
    private static final String TAG = "DrawView";

    private static final float MINP = 0.25f;
    private static final float MAXP = 0.75f;

    private Context context;
    private Paint mPaint = new Paint();
    private int[] pencolor = { Color.BLUE, Color.GREEN, Color.MAGENTA,
              Color.BLACK, Color.CYAN, Color.GRAY, Color.RED, Color.DKGRAY,
              Color.LTGRAY, Color.YELLOW };

    private Canvas  mCanvas;
    private Path    mPath;

    private ArrayList<Path> paths = new ArrayList<Path>();


    public void resetPenColor()
    {
        Random random = new Random();
        random.setSeed(System.currentTimeMillis());

        int color_index = random.nextInt(pencolor.length);
       //   Toast.makeText(context, "Pen Color "+color_index, Toast.LENGTH_SHORT).show();
        mPaint.setColor(pencolor[color_index]);
    }

    public page(Context context) {
        super(context);
        this.context = context;
        setFocusable(true);
        setFocusableInTouchMode(true);

       //this.setOnTouchListener(this);

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(Color.BLACK);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(6);
        mCanvas = new Canvas();
        mPath = new Path();
        paths.add(mPath);


    }



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

    public page(Context context, AttributeSet attrs, int defStyle) 
    {
        super(context, attrs, defStyle);
    }
        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh)
        {
            super.onSizeChanged(w, h, oldw, oldh);
        }

        @Override
        protected void onDraw(Canvas canvas) {            

            for (Path p : paths){
                canvas.drawPath(p, mPaint);
                Log.v("draw", "---line");
            }
        }

        private float mX, mY;
        private static final float TOUCH_TOLERANCE = 4;

        private void touch_start(float x, float y) {
            mPath.reset();
            mPath.moveTo(x, y);
            mX = x;
            mY = y;
        }
        private void touch_move(float x, float y) {
            float dx = Math.abs(x - mX);
            float dy = Math.abs(y - mY);
            if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
                mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
                mX = x;
                mY = y;
            }
        }
        private void touch_up() {
            mPath.lineTo(mX, mY);
            // commit the path to our offscreen
            mCanvas.drawPath(mPath, mPaint);
            // kill this so we don't double draw            
            mPath = new Path();
            paths.add(mPath);
        }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
         super.onTouchEvent(event);
         float x = event.getX();
          float y = event.getY();

          switch (event.getActionMasked()) {
              case MotionEvent.ACTION_DOWN:
                  touch_start(x, y);
                  invalidate();
                  break;
              case MotionEvent.ACTION_MOVE:
                  touch_move(x, y);
                  invalidate();
                  break;
              case MotionEvent.ACTION_UP:
                  touch_up();
                  invalidate();
                  break;
              case MotionEvent.ACTION_POINTER_DOWN:
                  resetPenColor();
                //  Toast.makeText(context, "Multitouch", Toast.LENGTH_SHORT).show();
                  invalidate();
                  break;
          }
          return true;
    }




}

最后是xml文件“book.xml”

public void onCreate(Bundle onsavestate)
    {
        super.onCreate(onsavestate);

        page pageview = new page(this);
        setContentView(R.layout.book);
}

日志文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <LinearLayout
        android:id="@+id/buttonlayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="@drawable/buttoncontainer"
        android:gravity="bottom"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/refresh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@color/white"
            android:src="@drawable/refresh"
            android:layout_marginLeft="4dp" />

        <ImageButton
            android:id="@+id/save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@color/white"
            android:src="@drawable/save"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp" />
    </LinearLayout> 

    <com.gsmappstabs.autographplease.page
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/buttonlayout" />

</RelativeLayout>

2 个答案:

答案 0 :(得分:2)

在XML文件中定义View时。第一个构造函数未被调用。您需要确保所有变量都是来自每个构造函数的init,如下所示:

public page(Context context) 
{
    super(context);
    init(context);   
}

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

public page(Context context, AttributeSet attrs, int defStyle) 
{
    super(context, attrs, defStyle);
    init(context);
}

private void init(Context context) {
    this.context = context;
    setFocusable(true);
    setFocusableInTouchMode(true);

    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(Color.BLACK);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(6);
    mCanvas = new Canvas();
    mPath = new Path();
    paths.add(mPath);
}

现在,无论调用哪个构造函数,您的mPath变量都将被初始化,并且不会有NPE。

另请注意:您执行page pageview = new page(this);没有任何意义,因为您的页面是来自XML文件的init。

答案 1 :(得分:0)

您只能在mPath构造函数中创建public page(Context context)字段,默认情况下它是null。但是,如果您使用的是xml,则不是布局inflater调用的构造函数。

您需要确保在其他构造函数public page(Context context, AttributeSet attrs, int defStyle)public page(Context context, AttributeSet attrs)中创建字段。

您在其他构造函数中调用super。您的意思是打电话给this(context)吗?