在android中实现倒计时的功能
实验效果:
(1)activity_main.xml文件中具体代码如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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="bzu.edu.cn.mytimer.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10"
android:textSize="100sp"
android:id="@+id/tvNumber"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start"
android:background="@null"
android:layout_below="@+id/tvNumber"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:onClick="start"
android:id="@+id/button"/>
</RelativeLayout>
(2)MainActivity中具体代码如下:
package bzu.edu.cn.mytimer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView tvNumber;
private int count=10;
private static final int UPDATE_TIME=1;
private Handler handler=new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
switch (msg.what){
case UPDATE_TIME:tvNumber.setText(count+"");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvNumber=(TextView)findViewById(R.id.tvNumber);
}
public void start(View view){
new Thread(new Runnable() {
@Override
public void run() {
while(count>0){
count--;
Message message=new Message();
message.what=UPDATE_TIME;
handler.sendMessage(message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}