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 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100