Android Studio之显示本地时间

 

•效果展示图

  

•代码

 1 package com.example.table;
 2 
 3 import android.os.Bundle;
 4 import android.os.Handler;
 5 import android.os.Message;
 6 import android.widget.Button;
 7 import android.widget.TextView;
 8 
 9 import androidx.appcompat.app.AppCompatActivity;
10 
11 import java.text.SimpleDateFormat;
12 import java.util.Date;
13 
14 public class ShowTimeActivity extends AppCompatActivity {
15 
16     private  Thread thread;
17     private Handler handler;  //异步消息处理器
18     private TextView tvTime;
19     private SimpleDateFormat sdf;
20     private boolean runing;
21     private TextView Tv1;
22     private Button Btn1;
23 
24     @Override
25     protected void onCreate(Bundle savedInstanceState) {
26         super.onCreate(savedInstanceState);
27         setContentView(R.layout.activity_show_time);
28 
29         tvTime = findViewById(R.id.tv_1);
30         sdf = new SimpleDateFormat("hh:mm:ss");
31         tvTime.setText(sdf.format(new Date()));
32 
33         //创建消息处理器 接受子线程发送的消息  根据它做出处理,跟新主界面的值
34         handler = new Handler(){
35             @Override
36             public void handleMessage(Message msg) {
37                 super.handleMessage(msg);
38                 if(msg.what == 1){
39                     tvTime.setText(sdf.format(new Date()));
40                 }
41             }
42         };
43 
44         thread = new Thread(new Runnable() {
45             @Override
46             public void run() {
47                 while (true){
48                     //让线程  发送消息
49                     handler.sendEmptyMessage(1);
50                     //让线程  睡眠500毫秒
51                     try {
52                         Thread.sleep(500);
53                     } catch (InterruptedException e) {
54                         e.printStackTrace();
55                     }
56                 }
57             }
58         });
59         //启动线程
60         thread.start();
61     }
62 }
ShwoTimeActivity.java
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:app="http://schemas.android.com/apk/res-auto"
 4     xmlns:tools="http://schemas.android.com/tools"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     tools:context=".ShowTimeActivity"
 8     android:background="#0288D1">
 9 
10     <TextView
11         android:id="@+id/tv_1"
12         android:layout_width="wrap_content"
13         android:layout_height="wrap_content"
14         android:layout_centerInParent="true"
15         android:textSize="30sp"/>
16 
17 </RelativeLayout>
activity_show_time.xml
posted @ 2020-02-29 22:07  MElephant  阅读(1757)  评论(0编辑  收藏  举报