简体   繁体   中英

How to call an Object's method that is defined in a different function? [Android]

I have this function called startTimer and I created an instance of the CountDownTimer class:

public void startTimer(View view){

    CountDownTimer myTime = new CountDownTimer(30000,1000) {

    }

}

The CountDownTimer has a method called cancel() that I want to invoke from a different method, resetTimer():

public void resetTimer() {

}

Both functions are contained within a single class. How do I call the cancel() method of CountDownTimer from the resetTimer()?

Make myTime a private global variable (global here meaning "outside of any function"):

public class myClass {
    private CountDownTimer myTime = ...

    public void startTimer(View view) {
        myTime.start();
    }

    public void resetTimer() {
        myTime. //etc...
    }
}
private CountDownTimer myTime;

public void startTimer(View view){

    myTime = new CountDownTimer(30000,1000) {

    }
}

public void reset() {
    myTime.cancel();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM