おそらく検索すれば簡単に出てくると思いますが。
System.currentTimeMillis();
このメソッドを使うと本体の時刻をms単位で返してきます(long)。
10分程度で簡単なものを作りました。
ボタンがトグルしてスタート・ストップの役割をします。
ストップウォッチみたいな感じです
例)class名 TestCurrentTimeProjectActivity
-------------------------------
public class TestCurrentTimeProjectActivity extends Activity {
/** Called when the activity is first created. */
long startTime;
long currentTime;
long sec;
Button button1;
TextView time;
int scn = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
time = (TextView) findViewById(R.id.time);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//ボタンをクリックしたらstartchek()のメソッドか呼ばれます
startchek();
}
});
}
private void startchek() {
if (scn == 0) {
//最初のボタンクリック時の現在の時刻を取得
startTime = System.currentTimeMillis();
scn = 1;
} else {
//2回目のボタンクリック時の時刻を取得
currentTime = System.currentTimeMillis();
//1回目と2回目の時刻を引いて1000ms秒(1秒)で割る。
sec=(currentTime - startTime)/1000;
//経過時間をテキストにセット
time.setText(String.valueOf(sec));
scn = 0;
}
}
}
-----------------------------------------------------
--------------------xml------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="count" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
------------------------------------------------------
0 件のコメント:
コメントを投稿