先看类:
public class MainActivity extends Activity {
Canvas canvas;
public int barometerRotationAngle=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Resources res = getResources();
canvas=new Canvas();
final Altimeter altimeter=(Altimeter) this.findViewById(R.id.altimeter);
final Button buttonup=(Button) this.findViewById(R.id.buttonup);
buttonup.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
barometerRotationAngle+=10;
altimeter.setBarometerRotationAngle(barometerRotationAngle);
}
});
}
}
}
程序在 altimeter.setBarometerRotationAngle(barometerRotationAngle);这里出现了空指针错误提示,但是alimeter类已经成功显示了图片,也就是说,他的onDraw()方法已被调用了。为什么在Onclick里面会变成了空指针?
不知道你的图片怎么显示的,你先确认
final Altimeter altimeter=(Altimeter) this.findViewById(R.id.altimeter);是否找到了对象
最简单就是自己跟踪一下,这也不复杂,看是这行报错了还是onDraw中报错了。
应该是找到对象了吧,否则,altimeter里面的onDraw不会被调用到。我画图片的方法就在onDraw里面。启动程序后,图片会显示出来,但是一按按钮就报空指针错误