ssummeraw 2013-01-18 08:38 采纳率: 10%
浏览 3228
已采纳

Android中秒表的停止问题

我在程序中创建了一个秒表 stopwatch,当然可以开始和停止。我用的以下的代码来实现这个功能。秒表可以开始,但是不能停止。

public class StopWatch2 extends Activity implements Runnable{

// text view influenced by the Thread
private TextView threadModifiedText;
int time=0;
Button b1,b2,b3;
/** Called when the activity is first created. */
Thread currentThread = new Thread(this);
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stopwatch);

    b1=(Button)findViewById(R.id.button1);
    b2=(Button)findViewById(R.id.button2);
    b3=(Button)findViewById(R.id.button3);
    threadModifiedText = (TextView) findViewById(R.id.textView1);
    b1.setOnClickListener(new View.OnClickListener() 
    {
        public void onClick(View view) 
        {
            currentThread.start();
        }

    });     
    b2.setOnClickListener(new View.OnClickListener() 
    {
        public void onClick(View view) 
        {
            currentThread.stop();
        }

    });               
}

//Method you must override to control what the Thread is doing
@Override
public void run(){
    try {
        while(true){
            currentThread.sleep(1000, 0);
            threadHandler.sendEmptyMessage(0);
        }
        // signaling things to the outside world goes like this  

    } catch (InterruptedException e) {
    }   
} 
private Handler threadHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        time++;
        threadModifiedText.setText(""+time);
    }
};
}

请求大家帮忙指出程序中的错误。谢谢!

  • 写回答

3条回答

  • hxn_217 2013-01-28 02:50
    关注

    你应该使用一个类变量boolean shouldRun = true ;在你的run()方法中while应该这样

    while(shouldRun)
    {
     //implementation
    }
    

    b2.onClickListener()改成shouldRun = false;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题