MainActivity.javapackage com.example.jishiqijindutiaodemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
public class MainActivity extends Activity {
// 声明 Chronometer 和Button对象
private Chronometer chronometer;
private Button button1, button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 实例化 Chronometer Button
chronometer = (Chronometer) findViewById(R.id.chronometer1);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
chronometer.setBase(SystemClock.elapsedRealtime());
// 开始计时
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
}
});
// 暂停计时
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
chronometer.stop();
}
});
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Chronometer
android:id="@+id/chronometer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:format="已用时间:%s"
android:textSize="30sp" />
<LinearLayout
android:id="@+id/LinlearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始计时"
android:textSize="25sp" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="结束计时"
android:textSize="25sp" />
</LinearLayout>
</LinearLayout>
|
|