我们开启一个线程,线程每隔一秒发送一次消息,我们在消息中更新textview上显示的时间就ok了。
上述就是android开发分享TextView显示系统时间(时钟功能带秒针变化的全部内容,如果对大家有所用处且需要了解更多关于Android学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
首先我们在布局文件中放一个textview用来显示时间,如下所示:
<linearlayout
xmlns:android=”https://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”@android:color/white”>
<textview
android:id=”@+id/mytime”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:gravity=”center”
android:textcolor=”@android:color/black”
android:textsize=”36sp”/>
</linearlayout>
之后我们写一个线程,线程里面无限循环,每隔一秒发送一个消息,其中由handler来处理显示的结果:
@override
public void run () {
do {
try {
thread.sleep(1000);
message msg = new message();
msg.what = msgkey1;
mhandler.sendmessage(msg);
}
catch (interruptedexception e) {
e.printstacktrace();
}
} while(true);
}
}
private handler mhandler = new handler() {
@override
public void handlemessage (message msg) {
super.handlemessage(msg);
switch (msg.what) {
case msgkey1:
long systime = system.currenttimemillis();
charsequence systimestr = dateformat.format(“hh:mm:ss”, systime);
mtime.settext(systimestr);
break;
default:
break;
}
}
};
之后我们可以在activity的oncreate方法中开启这个线程,这时我们可以看到一个数字时钟了:
super.oncreate(savedinstancestate);
setcontentview(r.layout.time);
mtime = (textview) findviewbyid(r.id.mytime);
new timethread().start();
}
整个activity的代码:
import android.app.activity;
import android.os.bundle;
import android.os.handler;
import android.os.message;
import android.text.format.dateformat;
import android.widget.textview;
public class testactivity extends activity {
private static final int msgkey1 = 1;
private textview mtime;
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.time);
mtime = (textview) findviewbyid(r.id.mytime);
new timethread().start();
}
public class timethread extends thread {
@override
public void run () {
do {
try {
thread.sleep(1000);
message msg = new message();
msg.what = msgkey1;
mhandler.sendmessage(msg);
}
catch (interruptedexception e) {
e.printstacktrace();
}
} while(true);
}
}
private handler mhandler = new handler() {
@override
public void handlemessage (message msg) {
super.handlemessage(msg);
switch (msg.what) {
case msgkey1:
long systime = system.currenttimemillis();
charsequence systimestr = dateformat.format(“hh:mm:ss”, systime);
mtime.settext(systimestr);
break;
default:
break;
}
}
};
}
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/addevelopment/939914.html