Android studio 小案例 (动态时间)
效果图
知识点的涉及
- 按钮(button)
- onClick
- 线程(Thread)
- 消息处理器(Handler)
在主布局文件activity_time.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:orientation="vertical"
android:gravity="center"
tools:context="com.example.administrator.nest.TimeActivity">
<TextView
android:id="@+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000"
android:textSize="70sp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center">
<Button
android:onClick="doStartt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn_begin"/>
<Button
android:onClick="doEnd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn_end"/>
</LinearLayout>
</LinearLayout>
在strings.xml文件中
<!--动态效果-->
<string name="time">动态效果</string>
<string name="str_time">动态时间</string>
<string name="btn_begin">开始</string>
<string name="btn_end">结束</string>
主窗口中TimeActivity中编写
package com.example.administrator.nest;
import android.app.Activity;
import android.os.Handler;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeActivity extends Activity {
private Thread thread;
private Handler handler; //异步消息处理器
private TextView tvTime;
private SimpleDateFormat sdf;
private boolean runing;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//利用布局资源文件设置用户界面
setContentView(R.layout.activity_time);
//通过资源标识获得控件实例
tvTime = (TextView) findViewById(R.id.tv_time);
sdf = new SimpleDateFormat("hh:mm:ss");
tvTime.setText(sdf.format(new Date()));
//创建消息处理器 接受子线程发送的消息 根据它做出处理,跟新主界面的值
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what == 1){
tvTime.setText(sdf.format(new Date()));
}
}
};
}
public void doStartt(View view){
//创建线程,定时发送消息
runing = true;
thread = new Thread(new Runnable() {
@Override
public void run() {
while (runing){
//让线程 发送消息
handler.sendEmptyMessage(1);
//让线程 睡眠500毫秒
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
//启动线程
thread.start();
}
public void doEnd(View view){
runing =false;
thread = null;
}
}
简单的动态时间案例就完成了,你get到了吗?