leyna1011
leyna1011
采纳率91.7%
2015-08-08 06:31 阅读 11.2k

Android自定义view,空指针异常求解决

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)
我知道错误的意思,也知道发生在哪儿,就是不知道怎么解决。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

4条回答 默认 最新

  • 已采纳
    w1213096890 德莱華 2015-08-08 12:24

    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">

    </LinearLayout>
    
    点赞 1 评论 复制链接分享
  • kangaroo835127729 crazy__chen 2015-08-10 12:08

    LinearLayout l = (LinearLayout)findViewById(R.layout.linearlayout);
    这句错了
    你应该在布局里面的id,而不是布局本身
    你可以给linearLayout添加一个id,就跟其他的控件一样,例如button
    也是需要添加id才能获取的
    关注我的专栏,http://blog.csdn.net/kangaroo835127729,谢谢

    点赞 1 评论 复制链接分享
  • qq_22605739 Al菜菜 2015-08-10 01:10

    findViewById只能用来找到控件,这个就只能去在view里面嵌入一个布局了,给这个布局指定id

    点赞 评论 复制链接分享
  • shuyou612 sendtion 2015-08-10 01:21

    LinearLayout l = (LinearLayout)findViewById(R.layout.linearlayout);
    应该是R.id.linearlayout,通过id找xml布局中的控件
    R.layout.linearlayout,这样是找xml布局

    点赞 评论 复制链接分享

相关推荐