1

我创建了HideImages()如下所示的函数。问题是,运行此代码会导致 NullPointerExcpection。当我注释掉这些setVisibility行时,它工作正常。我究竟做错了什么?

public class MainActivity extends Activity implements SurfaceHolder.Callback {
  ImageView img_w0, img_w1, img_w2;
  public void onCreate(Bundle savedInstanceState) {
    ImageView img_w0 = (ImageView)findViewById(R.id.img0);
    ImageView img_w1 = (ImageView)findViewById(R.id.img1);
    ImageView img_w2 = (ImageView)findViewById(R.id.img2);

    HideImages();

  }
  public void HideImages() {
    img_w0.setVisibility(View.INVISIBLE);
    img_w1.setVisibility(View.INVISIBLE);
    img_w2.setVisibility(View.INVISIBLE);
}
}
4

3 回答 3

3

将 ImageView 的所有引用设置为 Global as

public class MainActivity extends Activity implements SurfaceHolder.Callback {
  ImageView img_w0, img_w1, img_w2;
  public void onCreate(Bundle savedInstanceState) {
    img_w0 = (ImageView)findViewById(R.id.img0);
     img_w1 = (ImageView)findViewById(R.id.img1);
     img_w2 = (ImageView)findViewById(R.id.img2);

    HideImages();

  }
  public void HideImages() {
    img_w0.setVisibility(View.INVISIBLE);
    img_w1.setVisibility(View.INVISIBLE);
    img_w2.setVisibility(View.INVISIBLE);
}
}
于 2012-10-04T09:27:06.223 回答
1

我认为这可能会导致问题,因为您已经ImageView在 onCreate() 方法上方进行了初始化,这就是您在此处声明的原因,

img_w0 = (ImageView)findViewById(R.id.img0);
img_w1 = (ImageView)findViewById(R.id.img1);
img_w2 = (ImageView)findViewById(R.id.img2);
于 2012-10-04T09:26:28.443 回答
1

问题就在这里。您已经将ImageView对象声明为全局对象。而且,您再次在内部声明onCreate()

因此,只需删除其中的声明onCreate()并运行。如下图——

public void onCreate(Bundle savedInstanceState) {
    img_w0 = (ImageView)findViewById(R.id.img0);
    img_w1 = (ImageView)findViewById(R.id.img1);
    img_w2 = (ImageView)findViewById(R.id.img2);

}

于 2012-10-04T09:26:47.130 回答