阅读量:0
在Android中,实现倒计时可以使用Handler和Runnable来实现。以下是一个简单的示例代码:
public class CountDownTimerActivity extends AppCompatActivity { private TextView mTextViewCountdown; private int mCountdown = 10; private Handler mHandler; private Runnable mRunnable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_count_down_timer); mTextViewCountdown = findViewById(R.id.textview_countdown); mHandler = new Handler(); mRunnable = new Runnable() { @Override public void run() { if (mCountdown > 0) { mTextViewCountdown.setText(String.valueOf(mCountdown)); mCountdown--; mHandler.postDelayed(this, 1000); // 每隔1秒执行一次 } else { mTextViewCountdown.setText("倒计时结束"); } } }; mHandler.post(mRunnable); } @Override protected void onPause() { super.onPause(); mHandler.removeCallbacks(mRunnable); } }
在上面的示例中,首先在布局文件中定义了一个TextView用于显示倒计时,然后在Activity中创建了Handler和Runnable对象。在Runnable中实现了每隔1秒更新一次倒计时并更新TextView的逻辑。在Activity的onCreate()方法中调用Handler的post()方法来启动倒计时,同时在onPause()方法中移除Runnable以停止倒计时。