Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

findViewById 拿到空值的真正原因:找錯對象了(附自訂 View 生命週期陷阱)

編輯:關於 Android 程式設計

問題現場

這樣一段程式碼:

LinearLayout groupPollingAddress = (LinearLayout) findViewById(R.layout.fragment_field_list);

回傳值卻是 null。

排查過程

一開始我參考了几篇資料,包括 Stack Overflow 上關於 getActivity().findViewById(...) 回傳 null 的討論,以及介紹 inflate 與 findViewById 差異的文章,但都沒能解決問題。

後來換了關鍵字搜尋,才找到真正的線索:inflate 與 findViewById 是兩件不同的事。於是把寫法改成:

LayoutInflater inflater = (LayoutInflater) tabContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout groupPollingAddress = (LinearLayout) inflater.inflate(R.layout.fragment_field_list, null);

問題立刻解決。

同類的情況還有一處:

TextView tab1AllGroupPollingAddressLabel = (TextView) findViewById(R.id.lblVariable);

一樣回傳 null,改成從剛剛載入的父容器往下找就正常了:

TextView tab1AllGroupPollingAddressLabel =
        (TextView) groupPollingAddress.findViewById(R.id.lblVariable);

根本原因

其實我犯的錯誤很基礎:拿 R.layout 當成 R.id 用。findViewById 的參數必須是控制項的 id,傳入版面配置 id 當然找不到東西。

更普遍的原則是:findViewById 只會在「呼叫它的那個 View 的子樹」裡搜尋。如果你要的 View 不在 Activity 的主版面裡,而是透過 inflate 動態載入的,就必須先取得那個根 View,再從它往下找。

標準寫法如下:

LayoutInflater inflater = (LayoutInflater) tabContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout groupPollingAddress = (LinearLayout) inflater.inflate(R.layout.fragment_field_list, null);

先取得系統的 LayoutInflater,把 XML 實體化成真正的 View 物件,之後所有的子控制項都能從這個根節點往下取得。

額外提醒:自訂 View 中的空值陷阱

網路上常說自訂 View 裡 findViewById 拿到 null 是因為少了 super(context, attrs),但其實原因不只這一個。理解 View 生命週期的人應該知道:在自訂 View 的建構子裡呼叫 findViewById,幾乎必然為空——此時 View 還在初始化階段,尚未被附加到 Activity 的版面配置上,怎麼找都不會有結果。

正確做法是把這段邏輯搬到生命週期更晚的階段,例如:

protected void onAttachedToWindow() {
    super.onAttachedToWindow();
}

我就是把初始化程式碼移到這個回呼裡,問題才真正解決。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved