problem with stopWatch in android
in my app i have placed a stop watch with two buttons. The stop watch works in a proper way. But the problem is at start the timer looks as 0:0:0, when it starts counting the single digits are been changed over to double digits as 0:12:53.
this affects and disturbs the other layers too. At the start itself i want it to be displayed as 00:00:00 by default, so that i cant make changes in the layout.
but i don't know where to give the value for this. Following is my code
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(b1.getText().toString().equals("Start"))
{
if(currentThread.getState()==Thread.State.NEW)
{
currentThread.start();
shouldRun = true;
b1.setText("Stop");
}
else
{
shouldRun = false;
b1.setText("Stop");
}
}
else if(b1.getText().toString().equals("Stop"))
{
time=0;
time1=0;
time2=0;
}
}
});
b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(b2.getText().toString().equals("Pause"))
{
shouldRun = false;
b2.setText("Resume");
开发者_如何学运维 }
else if(b2.getText().toString().equals("Resume"))
{
shouldRun = true;
b2.setText("Pause");
}
}
});
}
@Override
public void run()
{
try
{
while(true)
{
while(shouldRun)
{
Thread.sleep(1000);
Log.e("run", "run");
threadHandler.sendEmptyMessage(0);
}
}
}
catch (InterruptedException e) {}
}
private Handler threadHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
sec=time2++;
if(sec == 59)
{
time2=0;
sec = time2++;
min=time1++;
}
if(min == 59)
{
time1=0;
min = time1++;
hr=time3++;
}
stopWatch.setText(""+hr+":"+min+":"+sec);
}
};
}
how to do this please help me............
This should do the work:
String time = String.format("%02d:%02d:%02d", hr, min, sec);
stopWatch.setText(time);
Or the one-line-version:
stopWatch.setText(String.format("%02d:%02d:%02d", hr, min, sec));
set the text like so
stopWatch.setText(""+(hr<10?"0"+hr:hr)+":"+(min<10?"0"+min:min)+":"+(sec<10?"0"+sec:sec));
will:
stopWatch.setText("00:00:00");
not do the trick when you initialise it?
It's simple you just add this code
private Handler threadHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
sec=time2++;
if(sec == 59)
{
time2=0;
sec = time2++;
min=time1++;
if(sec< 10)
sec= "0"+sec
}
if(min == 59)
{
time1=0;
min = time1++;
hr=time3++;
if(min< 10)
min= "0"+min
}
if(hr< 10)
hr= "0"+hr
stopWatch.setText(""+hr+":"+min+":"+sec);
}
};
精彩评论