开发者社区> 问答> 正文

Android自定义view空指针异常

蛮大人123 2016-03-13 19:47:23 2336
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);
    }
}
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)`
我知道错误的意思,也知道发生在哪儿,就是不知道怎么解决。

前端开发 数据建模 Android开发
分享到
取消 提交回答
全部回答(1)
  • 蛮大人123
    2019-07-17 19:03:04

    LinearLayout l = (LinearLayout)findViewById(R.layout.linearlayout);这段代码不对,虽然R.layout.linearlayout也是int型,但不是控件,findViewById是找控件的。可以这么解决,把这段代码改成 LinearLayout l = (LinearLayout)findViewById(R.id.lin);,然后在你的布局文件中添加一个LinearLayout的控件:
    `android:id="@+id/lin"
    android:layout_height="match_parent"
    android:layout_width="match_parent">`

    0 0

集结各类场景实战经验,助你开发运维畅行无忧

推荐文章
相似问题
推荐课程