在我的 onCreate()
方法中,我正在实例化一个 ImageButton
View :
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 对象。
关于如何做到这一点有什么建议吗?
最佳答案
我会将图像按钮设为一个实例变量,然后您可以根据需要从这两种方法中引用它。 IE。做这样的事情:
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 中相对昂贵,因此如果只在一个地方使用局部变量,则在方法中使用局部变量会更有效。
关于java - Android - 如何访问在 onResume 中的 onCreate 中实例化的 View 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4716482/