3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
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 程式設計教學

本文由kk665403pixnetnetblog提供 原文連結

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦