所以我试图在我的java项目中绘制一个矩形,由于某种原因我得到一个错误,应用程序关闭。错误是03-28 09:05:50.332:E / AndroidRuntime(4611):致命异常:主要 03-28 09:05:50.332:E / AndroidRuntime(4611):进程:com.Tripp.thebasics,PID:4611 03-28 09:05:50.332:E / AndroidRuntime(4611):java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.graphics.Paint.setColor(int)'
package com.Tripp.thebasics;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
public class DrawingView extends View {
Paint paint;
public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public DrawingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
Rect ourRect = new Rect();
ourRect.set(0,0,canvas.getWidth(),canvas.getHeight()/2 );
paint.setColor(Color.RED);
canvas.drawRect(ourRect, paint);
}
}
,这是下面那个类的按钮
public class JokeOfTheDay extends Activity {
DrawingView v;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
v = new DrawingView(this);
setContentView(v);
}
}
答案 0 :(得分:2)
在尝试使用之前,在构造函数中初始化paint变量。 paint = new Paint();
答案 1 :(得分:0)
以下是两个很好的资源,展示了如何创建自定义视图和绘画。
另请参阅此示例,了解如何创建PieChart视图: