在布局文件中放一个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动态显示当前年月日时分秒系统时间,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持!
总结以上是内存溢出为你收集整理的Android动态显示当前年月日时分秒系统时间(示例代码)全部内容,希望文章能够帮你解决Android动态显示当前年月日时分秒系统时间(示例代码)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)