定时器"/>
Android 线程+自制简易定时器
实现效果:利用通信机制hander的用法,设计一个定时器,点击开始计时按钮时,
中间数字从100开始倒计时,到0结束。
布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""xmlns:tools=""android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.example.administrator.youraisemeup.TimeActivity"><TextViewandroid:layout_width="match_parent"android:layout_height="200dp"android:id="@+id/tv"android:textSize="50sp"android:gravity="center"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="点击计时"android:id="@+id/button"android:layout_centerVertical="true"android:layout_centerHorizontal="true" />
</RelativeLayout>
代码:
package com.example.administrator.jreduch09;import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;public class TimeNActivity extends AppCompatActivity {private TextView show;private Button button;private Handler handler=new Handler(){@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);if(msg.what==1){show.setText(msg.what + "");}else{show.setText("倒计时结束");}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_time);show= (TextView) findViewById(R.id.show);button= (Button) findViewById(R.id.button);show.setText("100");button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {new Thread(new MyJob()).start();}});}public class MyJob implements Runnable{@Overridepublic void run() {int i=100;while (i>=0){try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}i--;Message message=new Message();message.what=i;handler.sendMessage(message);}}}
}
完成效果:
更多推荐
Android 线程+自制简易定时器
发布评论