MainActivity如下:
package cc.cv; import android.os.Bundle; import android.os.CountDownTimer; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.app.Activity; /** * Demo示例: * CountDownTimer完整详细示例 * 代码很简单,直接看注释即可 * * CountDownTimer是Android4.0引入的倒计时 */ public class MainActivity extends Activity { private Button mStartButton; private Button mCancelButton; private CountDownTimerSubClass mCountDownTimerSubClass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ mCountDownTimerSubClass=new CountDownTimerSubClass(15*1000, 1000); mStartButton=(Button) findViewById(R.id.startButton); //开始倒计时 mStartButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mCountDownTimerSubClass.start(); } }); //取消倒计时. //再次调用CountDownTimer的start时会重新开始倒计时. mCancelButton=(Button) findViewById(R.id.cancelButton); mCancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mCountDownTimerSubClass.cancel(); } }); } private class CountDownTimerSubClass extends CountDownTimer{ /** * millisInFuture 倒计时间 * countDownInterval 每两次倒计时之间的间隔 */ public CountDownTimerSubClass(long millisInFuture,long countDownInterval) { super(millisInFuture, countDownInterval); } /** * 倒计时结束 */ @Override public void onFinish() { System.out.println("结束"); } /** * 每一个倒计时间点到来时均会触发该方法 * millisUntilFinished表示整个倒计时剩余的时间 */ @Override public void onTick(long millisUntilFinished) { long remainedSeconds=millisUntilFinished/1000; System.out.println("剩余: "+remainedSeconds+" s"); } } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/startButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="100dp" android:text="start" /> <Button android:id="@+id/cancelButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_below="@id/startButton" android:layout_marginTop="100dp" android:text="cancel" /> </RelativeLayout>
时间: 2024-10-11 18:25:55