Android计时器控件Chronometer应用实例
时间:2021-01-16 12:29:06|栏目:Android代码|点击: 次
显示一个计时器开始计时,当计时器到达15s的时候,停止计时。此时页面多一个重置按钮,可再次进行计时。
页面布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:background="@drawable/bg" > <Chronometer android:id="@+id/chronometer" android:layout_marginTop="8dp" android:layout_marginLeft="5dp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/restart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="重置" android:visibility="gone" /> </LinearLayout>
事件响应
package com.example.chronometerdemo; import android.os.Bundle; import android.os.SystemClock; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Chronometer; import android.widget.Chronometer.OnChronometerTickListener; public class MainActivity extends Activity { Chronometer time=null; Button restart=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); time=(Chronometer) findViewById(R.id.chronometer); restart=(Button) findViewById(R.id.restart); //设置起始时间和时间格式,然后开始计时 time.setBase(SystemClock.elapsedRealtime()); time.setFormat("已用时间:%s"); time.start(); //给计时器添加监听器,当计时到达15s时,要重置 time.setOnChronometerTickListener(new OnChronometerTickListener() { @Override public void onChronometerTick(Chronometer arg0) { if(SystemClock.elapsedRealtime()-arg0.getBase()>=15000) { arg0.stop(); restart.setVisibility(View.VISIBLE); } } }); //给按钮添加重置的效果 restart.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { time.setBase(SystemClock.elapsedRealtime()); time.start(); restart.setVisibility(View.GONE); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
运行效果
栏 目:Android代码
下一篇:Android 中ListView setOnItemClickListener点击无效原因分析
本文标题:Android计时器控件Chronometer应用实例
本文地址:http://www.codeinn.net/misctech/45855.html