在此代码中获取空指针异常

时间:2013-03-15 06:55:07

标签: android

  public class StartDraw extends Activity  {




@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   // setContentView(R.layout.main);
    MyView view1 =new MyView(this);
   // view1.setBackgroundResource(R.drawable.ic_launcher);
    setContentView(view1);



}


 public class MyView extends View implements OnTouchListener{
    RelativeLayout.LayoutParams LP;  
    ViewGroup dlayout; 
      ImageView[] ActionI = new ImageView[4];
      ImageView[] ReciverI = new ImageView[4];
    public MyView(Context c) {
        super(c);
     //  dlayout = new ViewGroup(c); // if i use this then error shown {Cannot instantiate the type ViewGroup}
         LP = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
       //  ViewGroup dlayout = (ViewGroup)findViewById(R.id.dlayout);
         dlayout.setLayoutParams(LP); // at this position gettting null pointer exception

}

   @Override
    protected void onDraw(Canvas canvas) {
           paint.setStyle(Paint.Style.STROKE);
           paint.setStrokeWidth(2);
           paint.setColor(Color.GREEN);
           canvas.drawColor(Color.BLUE);

           canvas.drawLine(offset_x, offset_y, currentX, currentY, paint);

    }
}

3 个答案:

答案 0 :(得分:2)

的setContentView(R.layout.main);删除此评论并启用它

   setContentView(R.layout.main); remove this comments and enable it

的setContentView(R.layout.main);删除此评论并启用它

答案 1 :(得分:0)

您已注释掉dlayout初始化。因此它是null。在dlayout.setLayoutParams中导致 NullPointerException

如果您不理解这种因果关系,请扩展您的问题以澄清。但是,如果您不确定如何初始化dlayout变量, 会将其变为自己的 问题。

答案 2 :(得分:0)

您尝试设置未初始化的对象的属性

dlayout.setLayoutParams(LP);

取消注释上面的代码,错误应该修复。

//  ViewGroup dlayout = (ViewGroup)findViewById(R.id.dlayout);