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

In my onCreate () method, I create an ImageButton View image:

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 ImageButton properties with something like: @Override protected void onResume () {super.onResume (); ib.setImageURI (selectedImageUri); } // END onResume

But onResume does not have access to the ib ImageButton object. If it were a variable, I would just make it a class variable, but Android does not allow you to define a View object in a class.

Any suggestions on how to do this?

+3
source share
3 answers

I would make an image button of an instance variable, then you can access it from both methods if you want. i.e. 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);
}

, Android, , .

+4

findViewById() , . R.layout.layout_post .

findViewById() onResume(), , ib , , onCreate().

+3

. , 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);
    }
}
+1

Source: https://habr.com/ru/post/1785968/


All Articles