在安卓开发中,经常会使用计时和倒计时来开发,安卓为我们提供了非常便捷的控件
Chronometer,下面依次实现计时和倒计时:
计时功能:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context=".ChronometerActivity"> <Chronometer android:id="@+id/chronometer" android:layout_width="200dp" android:layout_height="200dp" android:gravity="center"/> </LinearLayout>
public class ChronometerActivity extends AppCompatActivity { private static final String TAG = "ChronometerActivity"; private Chronometer chronometer; int count=60; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chronometer); chronometer=(Chronometer)findViewById(R.id.chronometer); chronometer.start(); //停止计时 //chronometer.stop(); } }
倒计时功能:
public class ChronometerActivity extends AppCompatActivity { private static final String TAG = "ChronometerActivity"; private Chronometer chronometer; int count = 60; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chronometer); chronometer = (Chronometer) findViewById(R.id.chronometer); chronometer.start(); //停止计时 //chronometer.stop(); chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() { @Override public void onChronometerTick(Chronometer chronometer) { count--; chronometer.setText(count + ""); if (count == 0) { chronometer.stop(); } } }); } }