Timer实现倒计时

public class MainActivity extends AppCompatActivity {

    private TextView rx;
    int time = 5;
    //  定义总数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }

    private void initData() {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                time--;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        rx.setText(time + "S");
                        if (time == 0) {// 当数字为0 时候
                            timer.cancel();//  调用cancel关闭倒计时
                        }
                    }
                });

            }
        }, 1000/* 延时*/, 1000/*周期*/);
    }


    private void initView() {
        rx = (TextView) findViewById(R.id.rx);

    }
}

你可能感兴趣的:(Android,android)