2011-02-12 53 views
1

我正在查看ListActivity源代碼,並且我看到正在定義私人的Handler,並且Runnable被張貼到此處理程序的onContentChanged()方法中。瞭解ListActivity中的處理程序

我並不完全明白這一點,正如我所瞭解的那樣,處理程序在那裏用於線程間通信。這裏,處理程序和發佈的定義發生在同一個線程上,並且在post()調用中沒有指定延遲。我無法看到處理程序被用於其他任何事情。

我可能誤解了這裏處理程序的使用。爲什麼它按照這種方式完成,而不是直接運行mList.focusableViewAvailable()(可運行的內部調用)?結果會不一樣嗎?

下面的是什麼,我相信是ListActivity源代碼的相關部分:

public class ListActivity extends Activity { 

    protected ListView mList; 

    private Handler mHandler = new Handler(); 

    private Runnable mRequestFocus = new Runnable() { 
     public void run() { 
      mList.focusableViewAvailable(mList); 
     } 
    }; 

    /** 
    * Updates the screen state (current list and other views) when the 
    * content changes. 
    * 
    * @see Activity#onContentChanged() 
    */ 
    @Override 
    public void onContentChanged() { 
     super.onContentChanged(); 
     View emptyView = findViewById(com.android.internal.R.id.empty); 
     mList = (ListView)findViewById(com.android.internal.R.id.list); 
     if (mList == null) { 
      throw new RuntimeException(
        "Your content must have a ListView whose id attribute is " + 
        "'android.R.id.list'"); 
     } 
     if (emptyView != null) { 
      mList.setEmptyView(emptyView); 
     } 
     mList.setOnItemClickListener(mOnClickListener); 
     if (mFinishedStart) { 
      setListAdapter(mAdapter); 
     } 
     mHandler.post(mRequestFocus); 
     mFinishedStart = true; 
    } 

} 
+0

呃,你要給我NIGHTMARES!當我試圖學習如何使用ListActivity時,我經常看到`RuntimeException`。 – user432209 2011-02-12 16:41:41

+0

哈哈..對不起,老兄! :) – rogerkk 2011-02-12 16:47:35

回答

2

爲什麼運行一個命令完成它是這裏的方式,而不是mList.focusableViewAvailable()(在直接調用runnable)?結果會不一樣嗎?

您的疑慮不應該是Handler。您的關注應該是對post()的呼叫。 A Handler甚至不是真的需要,因爲post()可用於View - 但此代碼可能會在此日期前。

post()需要Runnable並將它放在主應用程序線程的消息隊列中。因此,直到目前在該隊列上的所有其他消息都得到處理(FIFO)之後,它纔會被處理。據推測,ListActivity需要在focusableViewAvailable()將成功工作之前先處理隊列上的其他消息。