Android倒计时(类似短信验证倒计时的实现)

来源:互联网 发布:ubuntu 安装ntfs 编辑:程序博客网 时间:2024/05/17 03:38

布局

    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="开始获取验证码"        android:onClick="onClick"/>    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/text3"/>
 private TextView text;    int nums=60;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        text = (TextView) findViewById(R.id.text3);    }    public void onClick(View view) {    //利用了Java.util中的Timer计时器,false的意思是不是后台线程,也可不写,默认不是后台线程        final Timer timer=new Timer(false);        //建立一个计划任务,一秒后执行        timer.schedule(new TimerTask() {            @Override            public void run() {                    nums--;                    //由于子线程不能更新UI,故用了Post                text.post(new Runnable() {                    @Override                    public void run() {                        text.setText(nums+"s");                        if(nums==0){                            timer.cancel();                        }                    }                });            }        },0,1000);    }

只是大致实现了倒计时的功能,具体细节可根据实际情况再做调整

1 0
原创粉丝点击