我需要在文本视图中显示当前时间,并且android中的时间每秒(如数字时钟)都会动态变化。我已经谷歌,但我没有得到的help.If谁有这方面的想法,请帮助我提前感谢。
发布于 2015-09-10 19:30:58
使用CountDownTimer类,为CountDownTimer生命传递一个巨大的值(这里我给了1000000000)。
示例代码::
CountDownTimer newtimer = new CountDownTimer(1000000000, 1000) {
public void onTick(long millisUntilFinished) {
Calendar c = Calendar.getInstance();
textView.setText(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND));
}
public void onFinish() {
}
};
newtimer.start();在关闭活动时,调用以下函数
newtimer.cancel();发布于 2012-05-17 18:54:49
这是代码..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread myThread = null;
Runnable myRunnableThread = new CountDownRunner();
myThread= new Thread(myRunnableThread);
myThread.start();
}
public void doWork() {
runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime= (TextView)findViewById(R.id.myText);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
txtCurrentTime.setText(curTime);
}catch (Exception e) {}
}
});
}
class CountDownRunner implements Runnable{
// @Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
doWork();
Thread.sleep(1000); // Pause of 1 Second
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}catch(Exception e){
}
}
}
}发布于 2016-12-04 03:46:20
使用TextClock。这将在没有单独代码的情况下动态变化。
<TextClock
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/textClock"
android:layout_weight="0.11"
android:textStyle="bold"
android:textSize="22sp"
android:format24hours="hh:mm:ss a EEE MMM d"/>
TextClock textClock = (TextClock) findViewById(R.id.textClock);
textClock.setFormat12Hour(null);
//textClock.setFormat24Hour("dd/MM/yyyy hh:mm:ss a");
textClock.setFormat24Hour("hh:mm:ss a EEE MMM d");https://stackoverflow.com/questions/10634231
复制相似问题