繁体   English   中英

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

[英]Android - How can I access a View object instantiated in onCreate in onResume?

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

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

    final ImageButton ib = (ImageButton) findViewById(R.id.post_image);
...

onResume ,我希望能够使用以下内容更改ImageButton的属性:

@Override
protected void onResume() {
    super.onResume();
    ib.setImageURI(selectedImageUri);
}

但是onResume无权访问ib ImageButton对象。 如果这是一个变量,我会简单地将其设为类变量,但 Android 不允许您在类中定义 View 对象。

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

我会将图像按钮设为实例变量,然后您可以根据需要从这两种方法中引用它。 即。 做这样的事情:

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

值得记住的是,尽管实例变量在 Android 中相对昂贵,因此如果只在一个地方使用,在方法中使用局部变量会更有效。

findViewById()不创建视图,它只是查找已经创建的视图。 它是通过扩大上一行中的布局R.layout.layout_post来创建的。

您可以简单地在onResume()方法中调用findViewById()以在该方法中获取对它的引用,或者您可以将ib更改为实例变量,以便在onCreate()以外的方法中可以访问它。

将声明从方法移动到类。 假设selectedImageUri在范围内......

public class MyApp extends Activity {
    ImageButton ib;

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

        ib = (ImageButton) findViewById(R.id.post_image);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ib.setImageURI(selectedImageUri);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM