Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

view

In my onCreate() method, I'm instantiating an ImageButton View:

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

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

In onResume, I want to be able to change the properties of the ImageButton with something like:

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

But onResume doesn't have access to the ib ImageButton object. If this were a variable, I'd simple make it a class variable, but Android does not allow you to define View object in the class.

Any suggestions on how to do this?

like image 843
Chris Avatar asked Jan 17 '11 18:01

Chris


People also ask

Which object is passed to onCreate () method?

The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity.

Why would you do the setContentView () in onCreate () of activity class?

As onCreate() of an Activity is called only once, this is the point where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById to programmatically interact with widgets in the UI, calling managedQuery(android.

What is the purpose of super onCreate () in android?

Q 9 – What is the purpose of super. onCreate() in android? The super. onCreate() will create the graphical window for subclasses and place at onCreate() method.

Is onResume called after onCreate?

onResume() will never be called before onCreate() . Save this answer. Show activity on this post. onResume() will always be called when the activity goes into foreground, but it will never be executed before onCreate() .


1 Answers

I would make the image button an instance variable, then you can refer to it from both methods if you like. ie. do something like this:

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

It's worth bearing in mind though that instance variables are relatively expensive in Android, so it's more efficient to use a local variable within the method if it's only used in one place.

like image 133
Captain Spandroid Avatar answered Oct 09 '22 14:10

Captain Spandroid