<Chronometer android:id="@+id/chronometer1" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<RelativeLayout 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" > <Chronometer android:id="@+id/chronometer1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="40dp" android:text="Chronometer" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/chronometer1" android:layout_marginLeft="32dp" android:layout_marginTop="34dp" android:text="Start" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button3" android:layout_alignBottom="@+id/button3" android:layout_centerHorizontal="true" android:text="Stop" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button1" android:layout_alignBottom="@+id/button1" android:layout_alignParentRight="true" android:layout_marginRight="22dp" android:text="Reset" /> </RelativeLayout>
package com.myapp; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.Button; import android.widget.Chronometer; import android.view.View; import android.os.SystemClock; import android.widget.Toast; public class MainActivity extends Activity { Button btn1,btn2,btn3; Chronometer chmeter1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // button1 Start btn1 = (Button) findViewById(R.id.button1); btn1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { chmeter1.start(); showElapsedTime(); } }); // button2 Stop btn2 = (Button) findViewById(R.id.button2); btn2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { chmeter1.stop(); showElapsedTime(); } }); // button3 Reset btn3 = (Button) findViewById(R.id.button3); btn3.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { chmeter1.setBase(SystemClock.elapsedRealtime()); showElapsedTime(); } }); // chronometer1 chmeter1 = (Chronometer) findViewById(R.id.chronometer1); } private void showElapsedTime() { long elapsedMillis = SystemClock.elapsedRealtime() - chmeter1.getBase(); Toast.makeText(MainActivity.this, "Elapsed milliseconds: " + elapsedMillis, Toast.LENGTH_SHORT).show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท