android基础控件(6)Chronometer实现计时器

1. 计时器(Chronometer)

1.1 activity_main

<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"
    tools:context=".MainActivity">
    <Chronometer
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:id="@+id/time1"/>
LinearLayout>
1.2 MainActivity
public class MainActivity extends AppCompatActivity {
    private Chronometer chronometer;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        chronometer=findViewById(R.id.time1);
        //获取系统时间
        chronometer.setBase(SystemClock.elapsedRealtime());
        //设置计时器格式
        chronometer.setFormat("%s");
        //开始计时器
        chronometer.start();
        //设置计时器监听事件
        chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                //当计时器计时到60s则设置计时器停止
                if((SystemClock.elapsedRealtime()-chronometer.getBase())>60000){
                    chronometer.stop();
                }
            }
        });
    }
}

你可能感兴趣的:(android开发)