Android使用handler实现简单的定时器,代码如下。
控件代码是:
java代码如下:
public class MainActivity extends AppCompatActivity {
private TextView tv_text;
private int count = 10;
private Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
countDown();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_text = (TextView) findViewById(R.id.tv_text);
Message msg = Message.obtain();
handler.sendMessageDelayed(msg, 1000);
}
public void countDown(){
if (count == 0){
return;
}
count--;
tv_text.setText(count+"");
Message msg = Message.obtain();
handler.sendMessageDelayed(msg, 1000);
}
}