一、创建MainActvity
二、编写视图(activity_shuji.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".shuji">
<TextView
android:id="@+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="70sp"
android:textColor="#ff0000" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="doStart"
android:text="@string/start" />
<Button
android:id="@+id/btn_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="doStop"
android:text="@string/stop" />
</LinearLayout>
</LinearLayout>
三、字符串资源文件strings.xml
动态显示时间
开始
停止
四.主界面shuji
package net.tp.xianxing;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
public class shuji extends AppCompatActivity {
private Thread thread;
private Handler handler;
private TextView tvTime;
private SimpleDateFormat sdf;
private boolean anniu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//利用布局资源文件设置用户界面
setContentView(R.layout.activity_shuji);
//通过资源标识获得控件实例
tvTime = findViewById(R.id.tv_time);
//实例化简单日期格式化对象
sdf = new SimpleDateFormat("hh:mm:ss");
tvTime.setText(sdf.format(new Date()));
//创建消息处理器,送的消息进行处理,更新主界面元素(标签)的内容
handler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
if(msg.what ==0x0001){
tvTime.setText(sdf.format(new Date()));
}
}
};
//创建线程,定时发送消息
}
public void doStart(View view){
anniu =true;
thread = new Thread(new Runnable() {
@Override
public void run() {
while(anniu){
//向主线程发送消息
handler.sendEmptyMessage(0x001);
//让线程睡眠500毫秒
try {
Thread.sleep(500);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
});
//启动线程
thread.start();
}
public void doStop(View view){
anniu = false;
thread =null;
}
protected void onDestroy(){
super.onDestroy();
//销毁线程
thread = null;
}
}
五、运行效果