倒计时

来源:互联网 发布:众泰e200和知豆 编辑:程序博客网 时间:2024/05/20 16:01

点击start,倒计时开始。


界面交互编写:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="bzu.edu.cn.mytimer.MainActivity">    <TextView        android:id="@+id/textView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="10"        android:textSize="50sp"        android:layout_centerVertical="true"        android:layout_centerHorizontal="true" />    <Button        android:id="@+id/button"        android:text="atart"        android:onClick="start"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="10dp"        android:layout_below="@id/textView"        android:layout_centerHorizontal="true" /></RelativeLayout>



MainActiviyt:

package bzu.edu.cn.mytimer;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.TextView;public class MainActivity extends AppCompatActivity {private TextView tvNumber;    private int count=10;    private static final int UPDATE_TIME=1;    private Handler handler=new Handler(){        @Override       public  void handleMessage(Message msg){           super.handleMessage(msg);            switch (msg.what)            {                case UPDATE_TIME:tvNumber.setText(count+"");            }       }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        tvNumber=(TextView)findViewById(R.id.textView);    }    public void start(View view)    {         new Thread(new Runnable() {             @Override             public void run() {               while(count>0)               {                   count--;                   Message message=new Message();                   message.what=UPDATE_TIME;                   handler.sendMessage(message);                   try {                       Thread.sleep(1000);                   } catch (InterruptedException e) {                       e.printStackTrace();                   }               }             }         }).start();    }}




原创粉丝点击