秒數倒數器
1.UI的xml檔
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="20sp"
android:text="準備倒數" />
<Button
android:id="@+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="33dp"
android:text="Start" />
</RelativeLayout>
2.主程式程式碼
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tv;
Button button;
MyHandler han;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) this.findViewById(R.id.textView1);
button = (Button) this.findViewById(R.id.submit);
han = new MyHandler();
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
new Thread(new Runnable() {
@Override
public void run() {
start();
}
}).start();
}
});
}
public void start() {
for (int i = 60; i >= 0; i--) {
try {
Message msg = new Message();
msg.arg1 = i;
han.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
int res = msg.arg1;
tv.setText("" + res);
}
}
}
沒有留言:
張貼留言