Android 线程+自制简易定时器

编程入门 行业动态 更新时间:2024-10-24 08:21:16

Android 线程+自制简易<a href=https://www.elefans.com/category/jswz/34/1768257.html style=定时器"/>

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 线程+自制简易定时器

本文发布于:2024-02-26 08:02:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1701803.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:定时器   线程   简易   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!