close

TimeTask其實就是一個時間執行緒,常被用於APP內部任何有時間機制的部分,像是馬錶、計時器、鬧鐘、遊戲一場多久時間需要結束等等....

這邊簡單的示範一下從10秒一直到數道0秒後接著重新一樣的動作

這邊廢話也不多說就直接上程式碼吧

示範

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/t1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

JAVA

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    Timer timer;//宣告一個時間函示
    int tt=10;//設置初始秒數
    TextView t1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t1=(TextView)findViewById(R.id.t1);
        timer = new Timer();//時間函示初始化
        //這邊開始跑時間執行緒
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tt--;//時間倒數
                        t1.setText(tt+"second");//讓TextView元件顯示時間倒數情況
                        //if判斷示裡面放置在時間結束後想要完成的事件
                        if (tt < 1) {
                            tt = 10; //讓時間執行緒保持輪迴
                        }
                    }
                });
            }
        };
        timer.schedule(task, 1000, 1000);//時間在幾毫秒過後開始以多少毫秒執行
    }
    }

相關文章:

[Android] Android 程式設計教學

本網站https://kk665403.pixnet.net/內之全部圖文,Saioyan梟夜所有,非經本人同意不得將全部或部分內容轉載於任何形式之媒體
Copyright © 2021 Saioyan. All rights reserved.
版權所有© 2021 Saioyan梟夜

arrow
arrow
    文章標籤
    Android
    全站熱搜

    Saioyan梟夜 發表在 痞客邦 留言(0) 人氣()