简体   繁体   English

如何调用在不同函数中定义的对象方法? [Android]

[英]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: 我有一个称为startTimer的函数,并创建了CountDownTimer类的实例:

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(): CountDownTimer有一个名为cancel()的方法,我想从其他方法resetTimer()调用:

public void resetTimer() {

}

Both functions are contained within a single class. 这两个函数都包含在一个类中。 How do I call the cancel() method of CountDownTimer from the resetTimer()? 如何从resetTimer()调用CountDownTimer的cancel()方法?

Make myTime a private global variable (global here meaning "outside of any function"): myTime设为私有全局变量(此处的全局变量表示“任何函数之外”):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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