Android sample code, kotlin

HUD/Spinner dialog

HUD/Spinner dialog

去背的 Spinner Dialog

開發 App 的時候,常常會需要使用轉圈圈動畫,常用來告知使用者需要等待一會,通常是用於 UI 流程控制。


這個原件在 iOS 裡稱之為 Activity Indicator 或是 Progress Indicator,而在 Android 裡則使用 ProgressBar 元件來製作,但是明明這個又不像是個 Bar … 而且會讓新手找不到該用那個元件!所以我們這裡就先稱之為 Spinner 吧~
ProgressBar 元件預設為Spinning轉圈圈動畫,可透過修改 style 屬性轉換為進度條等,不在這篇文章介紹範圍內,讀者可以自行試試。
要在畫面的中心顯示去背的 Spinner 動畫可以這麼作:

    val builder = AlertDialog.Builder(activity, R.style.IotecSpinnerTheme)
    val inflater: LayoutInflater = activity.layoutInflater
    val contentView: View = inflater.inflate(R.layout.iotec_hud_dialog, null)
    builder.setView(contentView)
    val dialog =  builder.create()
    dialog.setCancelable(false) // Block the UI
    dialog.show()
  • 1. 這裡調用了 IotecSpinnerTheme 的 Style 以及 iotec_hud_dialog 的 layout xml 檔,其中有去背的 xml 定義等。主要是將所有的 Dialog 顏色都設為 transparent 色 #00000000.
  • 2. 背景變暗的效果:透過設定xml中的 android:backgroundDimEnabled,可以開關背景變暗的效果。
  • 3. 透過 LayoutInflater 可以抓到 contentView, 方便再對 View 作其它的操作。
  • 4. dialog.setCancelable(false) 則可以擋住使用者自行關閉這個 Dialog。
  • 5. 要注意此操作必需要在 UI Thread 上執行,所以如果在其它的 Thread 上要呼叫開啟或關閉這個 dialog 時,必需要使用 runOnUiThread 的函式進行。比如說像是呼叫 Restful API 時,回傳的 callback 段並不會在 UI Thread 上。

同時顯示提示文字
要在轉圈圈時同時顯示 Loading.. ,雖然 ProgressBar 本身也有文字屬性,不過要比較自由的擺放文字的位置,還是另外作一個 TextView 會比較方便。
先編寫好 xml 之後,再透過下面的 code 來設定文字。

    val contentView: View = inflater.inflate(R.layout.iotec_hud_dialog, null)
    val textView = contentView.findViewById<TextView>(R.id.loading_msg)
    textView?.text = "Loading"

變更 Spinner 顏色
要變更 Spinner 顏色,有二個方法:

1. 修改 xml, 設定其 indeterminateTint 的顏色

    android:indeterminateTint="#FF0000"

2. 程式設定 indeterminateTintList 的值

    val progressBar = contentView.findViewById<ProgressBar>(R.id.loader)
    progressBar.indeterminateTintList = ColorStateList.valueOf(color)
    progressBar.indeterminateTintMode = PorterDuff.Mode.SRC_IN

這二種方法,建議若要寫成 Helper function, 用程式設定比較好;若沒有的話,就多建幾個 xml 會比較好 trace。

同一個專案的 Spinner 通常只會有同一個 style, 在專案一開始時,調好一個合用的 Spinner ,包括顏色,字型大小等等,之後就一路沿用下去,會省事很多。

Sample project :

https://github.com/orangedream/IotecDialogExample/tree/hud

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.