android学习笔记13:计时器
计时器程序,打击启动,计时器开始计时,20秒之后自动停止,使用了计时器控件
package org.crazyit.time;
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;
import android.widget.Chronometer.OnChronometerTickListener;
public class ChronometerTest extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取计时器组件
final Chronometer ch = (Chronometer)findViewById(R.id.test);
//获取“开始”按钮
Button start = (Button)findViewById(R.id.start);
start.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
//设置开始计时时间
ch.setBase(SystemClock.elapsedRealtime());
//启动计时器
ch.start();
}
});
//计时器易做图
ch.setOnChronometerTickListener(new OnChronometerTickListener()
{
@Override
public void onChronometerTick(Chronometer ch)
{
//如果从开始计时到现在超过了20s。
if(SystemClock.elapsedRealtime() - ch.getBase()
> 20 * 1000)
{
ch.stop();
}
}
});
}
}
package org.crazyit.time;
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;
import android.widget.Chronometer.OnChronometerTickListener;
public class ChronometerTest extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取计时器组件
final Chronometer ch = (Chronometer)findViewById(R.id.test);
//获取“开始”按钮
Button start = (Button)findViewById(R.id.start);
start.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
//设置开始计时时间
ch.setBase(SystemClock.elapsedRealtime());
//启动计时器
ch.start();
}
});
//计时器易做图
ch.setOnChronometerTickListener(new OnChronometerTickListener()
{
@Override
public void onChronometerTick(Chronometer ch)
{
//如果从开始计时到现在超过了20s。
if(SystemClock.elapsedRealtime() - ch.getBase()
> 20 * 1000)
{
ch.stop();
}
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
>
<!--计时器控件 -->
<Chronometer
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12pt"
android:textColor="#ffff0000"
/>
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动"
/>
</LinearLayout>
摘自 hn307165411的专栏
补充:移动开发 , Android ,