package com.drawview.drawview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linearlayout);
LinearLayout l = (LinearLayout)findViewById(R.layout.linearlayout);
DrawView dv = new DrawView(this);
dv.setMinimumHeight(300);
dv.setMinimumWidth(300);
l.addView(dv);
}
}
package com.drawview.drawview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DrawView extends View{
private float currentX = 30;
private float currentY = 30;
Paint p = new Paint();
public DrawView(Context context) {
super(context);
}
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
currentX = event.getX();
currentY = event.getY();
invalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
p.setColor(Color.MAGENTA);
canvas.drawCircle(currentX,currentY,15,p);
}
}
【错误提示】
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference
at com.drawview.drawview.MainActivity.onCreate(MainActivity.java:17)
我知道错误的意思,也知道发生在哪儿,就是不知道怎么解决。