Android中实现倒计时

时间:2021-02-24 22:00:39

1.需求

弹出提示的dialog,实现倒计时,结束后关闭dialog

2.dialog界面布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="500dp"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="@+id/counter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/greater_magrin_space"
android:gravity="center"
android:text="10s"
android:textSize="@dimen/content_text_size_standard"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/greater_magrin_space"
android:gravity="center"
android:text="@string/title_sale"
android:textSize="@dimen/content_text_size_standard"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/content_header_space"
android:gravity="center"
android:text="@string/processing"
android:textSize="@dimen/content_text_size_standard"/>
<TextView
android:layout_width="match_parent"
android:layout_height="@dimen/greater_magrin_space" />

</LinearLayout>

3.AndroidManifest.xml文件设置

<activity android:name=".ProcessingDialogActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar"
android:screenOrientation="portrait"/>

4.ProcessingDialogActivity实现

另开一个线程实现倒计时功能不占用UI线程

 

public class ProcessingDialogActivity extends Activity{
private TextView counter;
private int count = 10;
private boolean isEnd = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_processingdialog);

counter = (TextView)findViewById(R.id.counter);
new Thread(new CounterThread()).start();
}
Handler handler = new Handler(){
public void handleMessage(Message message){
switch (message.what){
case 0:
if (count == 0){
finish();
}
counter.setText(String.valueOf(count)+"s");
break;
default:
break;
}
}
};
public class CounterThread implements Runnable{
@Override
public void run(){
while (!isEnd){
try {
Thread.sleep(1000);
count--;
if (count < 1){
isEnd = true;
}
Message msg = new Message();
msg.what = 0;
handler.sendMessage(msg);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}

 

 


效果如下图
Android中实现倒计时