使ImageView不受方法影响

时间:2012-10-04 09:24:34

标签: android android-layout

我创建了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);
}
}

3 个答案:

答案 0 :(得分:3)

将ImageView的所有引用设为全局

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);
}
}

答案 1 :(得分:1)

我认为这可能是问题所在,因为您已经在onCreate()方法之上初始化ImageView,这就是您在此声明的原因,

img_w0 = (ImageView)findViewById(R.id.img0);
img_w1 = (ImageView)findViewById(R.id.img1);
img_w2 = (ImageView)findViewById(R.id.img2);

答案 2 :(得分: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);

}