如何使用ProgressDialog(kotlin)

如何使用ProgressDialog(kotlin)

情境

如果想要跑一個網路下載,或者處理一個運算量比較大的事件,我們通常要通知使用者目前正在下載或運算,
因此,我們會彈出一個對話框告知程式還有在跑,避免使用者會以為程式當掉,而把程式強制關閉,這樣就是ProgressDialog 使用時機。

完整程式碼

你也可以直接從 GitHub 直接下載程式碼或觀看。

程式碼說明

首先我們在 xml 裡面設置一個 Button。

<?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"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/waitButton"
        android:text="Hello World!"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>

然後在 onCreate 裡面,設置一個事件,當我們按下這個 Button 就會跳出一個 ProgressDialog 的視窗。
接著我們就設定一個執行緒來處理,當三秒鐘過後,就把這個 Dialog 關閉。

class MainActivity : AppCompatActivity() {  
  
 override fun onCreate(savedInstanceState: Bundle?) {  
  super.onCreate(savedInstanceState)  
  setContentView(R.layout.activity_main)  
  waitButton.setOnClickListener {  
   val dialog = ProgressDialog.show(this@MainActivity,"讀取中", "請等待3秒...", true)  
   Thread(Runnable {  
    try {  
     Thread.sleep(3000)  
    } catch (e: Exception) {  
     e.printStackTrace()  
    } finally {  
     dialog!!.dismiss()  
    }  
   }).start()  
  }  
 }  
}

當按下 Button 以後就會跳出 ProgressDialog 了。