这个demo演示了计时器的简单用法。
android:format="@string/initial_format"
通过该属性为计时器设置显示格式。
<string name="initial_format">Initial format:<xliff:g id="initial-format">%s</xliff:g></string>
Xliff是XML Localization Interchange File Format 的缩写,名为XML本地化数据交换格式。
* %s表示字符串格式。
* 需要注意的是:在String里要增加XLIFF的 xmlns:
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
public class MainActivity extends Activity implements OnClickListener {
private Chronometer mChronometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mChronometer=(Chronometer) findViewById(R.id.chronometer);
Button bt;
bt = (Button) findViewById(R.id.start);
bt.setOnClickListener(this);
bt = (Button) findViewById(R.id.stop);
bt.setOnClickListener(this);
bt = (Button) findViewById(R.id.reset);
bt.setOnClickListener(this);
bt = (Button) findViewById(R.id.format);
bt.setOnClickListener(this);
bt = (Button) findViewById(R.id.clear);
bt.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
mChronometer.start();
break;
case R.id.stop:
mChronometer.stop();
break;
case R.id.reset:
//设置基准时间为从应用起动到当前的时间间隔
mChronometer.setBase(SystemClock.elapsedRealtime());
break;
case R.id.format:
mChronometer.setFormat("Formatted time: %s");
break;
case R.id.clear:
mChronometer.setFormat(null);
break;
default:
break;
}
}
}
activity_main.xml
<LinearLayout 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"
android:orientation="vertical" >
<Chronometer
android:id="@+id/chronometer"
android:layout_marginBottom="30dp"
android:layout_marginTop="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:format="@string/initial_format" />
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"/>
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"/>
<Button
android:id="@+id/reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"/>
<Button
android:id="@+id/format"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set Format String"/>
<Button
android:id="@+id/clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Format String"/>
</LinearLayout>