如何在Android中設定延遲?


在某些情況下,我們需要一段時間後更新UI來解決這個問題。本例演示如何在Android中設定延遲。

步驟1 - 在Android Studio中建立一個新專案,轉到檔案⇒新建專案,並填寫所有必需的詳細資訊以建立一個新專案。

步驟2 - 將以下程式碼新增到res/layout/activity_main.xml。

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:id = "@+id/parent"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:gravity = "center"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/textChanger"
      android:layout_margin = "20dp"
      android:textAlignment = "center"
      android:text = "Initial text"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content" />
</LinearLayout>

在上面的程式碼中,我們使用了TextView,它最初顯示“初始文字”,一段時間後將更新為新文字。

步驟3 - 將以下程式碼新增到src/MainActivity.java

package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   int view = R.layout.activity_main;
   TextView textChanger;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(view);
      textChanger = findViewById(R.id.textChanger);
      Handler handler = new Handler();
      handler.postDelayed(new Runnable() {
         @Override
         public void run() {
            textChanger.setText("After some delay, it changed to new text");
         }
      }, 5000);
   }
}

在上面的程式碼中,我們使用了Handler來維護延遲,如下所示:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
   @Override
   public void run() {
      textChanger.setText("After some delay, it changed to new text");
   }
}, 5000);

在上面的程式碼中,5000毫秒後更新文字。讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要從Android Studio執行應用程式,請開啟專案的其中一個活動檔案,然後點選執行  工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕:

最初,它將顯示如上所示的文字。一段時間後,它將更新文字,如下所示:

點選此處下載專案程式碼

更新於:2019年7月30日

5K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告