I know this is a little dumb, but how do you do this? I’ve “RTFM” but I still don’t understand concepts like this just don’t exist in the languages I’m used to programming. Anyway, my question is simple: how does one properly set a global variable which can be used by all public void functions inside that class?
Here is some example code, I will highlight the redundancy in case you don’t see it:
public class baketimer extends Activity implements OnClickListener {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button cupcake1 = (Button) this.findViewById(R.id.cupcake1);
cupcake1.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.cupcake1:
final Button cupcake1 = (Button) this.findViewById(R.id.cupcake1);
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
cupcake1.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
cupcake1.setText("Done!");
}
}.start();
Toast.makeText(this, "Mmm cupcakes!", Toast.LENGTH_SHORT).show();
break;
How would I go about declaring cupcake1 for the entire class?
Thanks in advance!
Declare the variable inside the class and outside any function, but not necessarily static.
Use static (
static Button cupcake = ...) if you want the variable to be shared by ALL objects – aka ALL instances of the class – in your program. Otherwise, don’t use static, so that the variable only belongs to that object.