跳到主要內容

清空 Handler 的 message queue

寫 Android 多執行緒的程式時,我最常使用的是 Thread-Handler 架構。某天遇到了一個情形:在特定時間點清空 message queue,讓 Handler 都不處理還留著的 event。有一個方法可以做到,就是 removeCallbacksAndMessages。API 說明如下:

public final void removeCallbacksAndMessages (Object token)

Added in API level 1
Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.
因此,我們只要使用 handler.removeCallbacksAndMessages(null),就可以讓 Handler 不處理還 queue 住的 event。

留言

這個網誌中的熱門文章

如何把 Status Bar 變透明

        Android 從 4.4 (KitKat, api level 19) 後才支援這個功能, 到了 5.0 (Lollipop, api level 21) 自訂性更高, 可以讓我們設定各種顏色, 當然也包含透明色。以下分別介紹如何使用這兩種版本的方法。         方法1: 利用 attribute " android:windowTranslucentStatus ", 在 style.xml 加上這個 attribute 就好。要注意的是 Android 版本要在 4.4 以上才可以用這個 attribute: <resources> <!-- Base application theme for API 19+. This theme completely replaces AppTheme from res/values/styles.xml on API 19+ devices. --> <style name="AppTheme" parent="@style/AppBaseTheme"> <!-- API 19 theme customizations can go here. --> <item name="android:windowTranslucentStatus">true</item> </style> </resources>         下面的圖分別為 4.4 跟 5.0 的手機使用這個 attribute 的結果:         因為設定了這個 attribute, 畫面會從 status bar 下方開始畫。要解決這個有兩種方法, 第一個是在 layout 畫面設定 attribute "android:fitsSystemWindows " <RelativeLayout xmlns:android="http:...

探討 LayoutInflater 的 inflate method

        在 Android 程式裡要動態新增 View,最直接的方法就是使用 LayoutInflater 提供的 inflate method。比較常用的有以下兩個 method: inflate(int resource, ViewGroup root) inflate(int resource, ViewGroup root, boolean attachToRoot)         第一個參數 resource,就是 layout xml file,如 R.layout.your_file。第二個參數 root,指的是這個 inflate 的 view,要成為哪個 view 的 child view。最後一個參數 attachToRoot 是 inflate 的 view 是否要 attach 到 root view,這會影響到回傳的是哪個 view。假如 attachToRoot 為 true,則最後回傳的 view 為 root view (就是第二個參數的 view);反之就是回傳 inflate 的 view。         第二個參數 ViewGroup root 需要特別說明一下,因為這會影響到如何 inflate 新的 view 出來。android 的 view 是有階層 (hierarchy) 的,因此 parent view 的屬性 (attribute) 會影響到 child view 。假如你是如以下兩種方式使用 inflate method的話: View view1 = LayoutInflater.from(mContext).inflate(R.layout.your_file, null) View view2 = LayoutInflater.from(mContext).inflate(R.layout.your_file, null, false)         因為沒有 root view,系統沒辦法把 inflate view 的屬性正確設定,因此系統會把 inflate view 的屬性設為 null,這會導致 inflate ...

動態更新 ViewPager 的目前顯示頁面

        ViewPager 在 Android 裡是一個很好用的元件,使用者只要左右滑動,就可以顯示多頁的資訊。假如你的資料是從網路取得,如圖片,當使用者滑到還沒載入完成的頁面時,該怎麼辦呢?         雖然 ViewPager 會動態更新頁面,但是當下顯示的頁面是不會更新的。要達到上述的目的,我們要做一些事。ViewPager 主要是由 PagerAdapter 來處理內部的資料的,因此我們要從它下手。         PagerAdapter 有一個 method:getItemPosition。看 API 說明應該是用來判斷目前頁面的內容位置是否有變,但是也可以用它來滿足我們的要求,pseudo code 如下: public int getItemPosition(Object object) {         if ( 你的資料準備好了 )         {                 return POSITION_NONE;         }         else         {                 // 資料還沒準備好,此頁面維持不變                 return POSITION_UNCHANGED;         } }         雖然 overwrite 了 getItemPosition,但是這個 method 並不是我們主動去 invoke 的,PagerAdapter 提供了另一個 method 可以讓我們通...