栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从其他类及其TextView触发计时器,并分别在另一个xml和类中实现?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从其他类及其TextView触发计时器,并分别在另一个xml和类中实现?

正Piyush Gupta所提到的,您应该在您的容器中调用该

setTimer()
方法。
onResume``QuestionActivity

来自Android开发者文档:

(onResume is) called for your activity to start interacting with the user.This is a good place to begin animations, open exclusive-access devices (suchas the camera), etc.

在你的代码也应该使

counterTimer
你在使用
setTimer()
一个 类成员 ,而不是一个局部变量;
如果不这样做,则在
setTimer()
呼叫完成后它将超出范围,并且您对其的访问将丢失。

因此,您需要将以下内容添加到

QuestionActivity

public class QuestionActivity extends Activity implements OnClickListener{    // NEW: add counterTimer as a member    private CountDownTimer counterTimer;    // NEW: implement onResume    @Override    public void onResume() {        setTimer();        super.onResume();    }    // CHANGE: setTimer should be changed as follows    public void setTimer() {        long finishTime = 5;        // NOTE: use the member, instead of a local        counterTimer = new CountDownTimer(finishTime * 1000, 1000) { public void onFinish() {     //pre to execute when time finished } public void onTick(long millisUntilFinished) {     int seconds = (int) (millisUntilFinished / 1000);     int minutes = seconds / 60;     seconds = seconds % 60;     if (seconds < 10) {         txtTimer.setText("" + minutes + ":0" + seconds);     } else {         txtTimer.setText("" + minutes + ":" + seconds);     } }        };        counterTimer.start();    }}

这上面的例子使用你的代码,因为它是现在,但我会建议你在创建定时器

onCreate
一切,这是目前在SetTimer的(),除了使用类成员来存储它(即
counterTimer.start();
调用。然后,只需用
counterTimer.start();
onResume
。也许添加一个
counterTimer.cancel()
呼叫,
onPause
以便当活动失去焦点时计时器结束。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/368770.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号