如何從 Android 執行緒中顯示 Toast 訊息?


此示例演示如何在 Android 中從執行緒中顯示 Toast 訊息。

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

步驟 2 − 將以下程式碼新增到 res/layout/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:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
</RelativeLayout>

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

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   Toast toast;
   Thread thread;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      toast = Toast.makeText(this, "This is a toast from Thread", Toast.LENGTH_SHORT);
      thread = new Thread(new Runnable() {
         @Override
         public void run() {
            for (int i=0; i<1000; i++){
               try {
                  Thread.sleep(1000);
                  toast.show();
                  Thread.sleep(1000);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
            }
         }
      });
      thread.start();
   }
}

步驟 4 - 將以下程式碼新增到 androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

讓我們嘗試執行你的應用程式。我假設你已將實際的 Android 移動裝置與你的電腦連線起來。要從 Android Studio 執行應用,請開啟你的專案中一個 activity 檔案,然後點選工具欄上的執行 播放圖示 圖示。將移動裝置選為選項,然後檢查移動裝置,它將顯示預設螢幕 –

點選 此處 下載專案程式碼。

更新於: 2020 年 7 月 1 日

1K+ 瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告