Android - 如何在onResume中访问onCreate中实例化的View对象?

Chr*_*ris 4 java android views

在我的onCreate()方法中,我正在实例化一个ImageButton视图:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_post);

    final ImageButton ib = (ImageButton) findViewById(R.id.post_image);
...
Run Code Online (Sandbox Code Playgroud)

在onResume中,我希望能够用以下内容更改ImageButton的属性:@Override protected void onResume(){super.onResume(); ib.setImageURI(selectedImageUri); } // END onResume

但onResume无法访问ib ImageButton对象.如果这是一个变量,我会简单地将它变成一个类变量,但是Android不允许你在类中定义View对象.

有关如何做到这一点的任何建议?

小智 5

我会将图像按钮设为实例变量,如果您愿意,可以从两种方法中引用它.即.做这样的事情:

private ImageButton mImageButton = null;

public void onCreate(Bundle savedInstanceState) {
  Log.d(AntengoApplication.LOG_TAG, "BrowsePicture onCreate");
  super.onCreate(savedInstanceState);
  setContentView(R.layout.layout_post);

  mImageButton = (ImageButton) findViewById(R.id.post_image);
  //do something with mImageButton
}

@Override
protected void onResume() {
  super.onResume();
  mImageButton = (ImageButton) findViewById(R.id.post_image);
  mImageButton.setImageURI(selectedImageUri);
}
Run Code Online (Sandbox Code Playgroud)

值得注意的是,虽然Android中的实例变量相对昂贵,但如果它只在一个地方使用,那么在方法中使用局部变量会更有效.