Can I initialize the same image twice in different functions in Android studio

Viewed 30

I have an ImageButton that I initialized in my OnCreate() function, and I also want to use it in a separate function, when my spinner is activated, but I can't access the imagebutton that has been initalized.

Can I just initalize the image button again in the OnSpinnerSelection() function or is that bad practice?

Thanks!

1 Answers

A better way to do would be to initialize the ImageButton outside the onCreate method. Then, it becomes a global variable and can be used in any method.

Like this :

ImageButton im;

@Override

protected void onCreate (Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

// set content view

im = (ImageButton)findViewbyId(R.id.<id>);

// other code 

}

Related