Android动态显示当前年月日时分秒系统时间(示例代码)
程序员文章站
2023-12-04 10:51:04
在布局文件中放一个textview用来显示时间,如下所示:
在布局文件中放一个textview用来显示时间,如下所示:
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://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发消息,来实时的更新textview上显示的系统时间:
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: mtime.settext(gettime()); break; default: break; } } }; //获得当前年月日时分秒星期 public string gettime(){ final calendar c = calendar.getinstance(); c.settimezone(timezone.gettimezone("gmt+8:00")); string myear = string.valueof(c.get(calendar.year)); // 获取当前年份 string mmonth = string.valueof(c.get(calendar.month) + 1);// 获取当前月份 string mday = string.valueof(c.get(calendar.day_of_month));// 获取当前月份的日期号码 string mway = string.valueof(c.get(calendar.day_of_week)); string mhour = string.valueof(c.get(calendar.hour_of_day));//时 string mminute = string.valueof(c.get(calendar.minute));//分 string msecond = string.valueof(c.get(calendar.second));//秒 if("1".equals(mway)){ mway ="天"; }else if("2".equals(mway)){ mway ="一"; }else if("3".equals(mway)){ mway ="二"; }else if("4".equals(mway)){ mway ="三"; }else if("5".equals(mway)){ mway ="四"; }else if("6".equals(mway)){ mway ="五"; }else if("7".equals(mway)){ mway ="六"; } return myear + "年" + mmonth + "月" + mday+"日"+" "+"星期"+mway+" "+mhour+":"+mminute+":"+msecond; } }
以上所述是小编给大家介绍的android动态显示当前年月日时分秒系统时间,希望对大家有所帮助