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

Android LayoutInflater 完全解析:三種取得方式與服務名稱速查

編輯:關於 Android 程式設計

佈局檔能搞定的情況是常態,但難免遇到要依資料動態決定視圖結構的場景,這時就得靠 LayoutInflater 在程式碼裡把 XML 變成 View 物件。

LayoutInflater 與 findViewById 的分工

顧名思義,Inflate 就是「充氣、撐開」,把一份 XML 描述展開成真正的 View 樹。它和 findViewById() 常被拿來對比,但兩者層次不同:LayoutInflater 拿到的是整份佈局檔對應的 View 物件,而 findViewById() 是在既有 View 樹裡按 id 找某個具體控制項。前者造樹,後者摘葉。

最常見的使用場合是 BaseAdapter.getView():清單項的佈局不可能寫死在 Activity 裡,必須由 Adapter 為每一列即時 inflate 出來。

三種取得方式

public class LayoutInflaterActivity extends Activity {
    private EditText et;
    private Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 第一種:LayoutInflater.from(this)
        LayoutInflater inflater = LayoutInflater.from(this);
        View layout = inflater.inflate(R.layout.main, null);

        // 第二種:Activity.getLayoutInflater()
        // LayoutInflater inflater = getLayoutInflater();
        // View layout = inflater.inflate(R.layout.main, null);

        // 第三種:直接從系統服務取
        // LayoutInflater inflater =
        //     (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        // View layout = inflater.inflate(R.layout.main, null);

        // 拿到整份佈局後,就能自行組裝、客製控制項
        et = (EditText) layout.findViewById(R.id.edittext);
        et.setBackgroundColor(Color.YELLOW);

        btn = (Button) layout.findViewById(R.id.btn);
        btn.setBackgroundColor(Color.CYAN);

        setContentView(layout);
    }
}

三種寫法最終都指向同一個物件,本質上第一種就是第三種的語法糖:from() 內部呼叫的是 Context 的 getSystemService(LAYOUT_INFLATER_SERVICE),第二種則是 Activity 為自己封裝好的便捷方法。日常開發用第一種最直觀。

順帶整理:getSystemService 常見服務名

getSystemService 是 Context 上的方法,依傳入的名稱常數回傳對應的系統服務物件,這些常數都定義在 Context 類別中:

傳入名稱回傳物件用途
WINDOW_SERVICEWindowManager管理已開啟的視窗
LAYOUT_INFLATER_SERVICELayoutInflater取得 XML 定義的 View
ACTIVITY_SERVICEActivityManager管理應用程式的系統狀態
POWER_SERVICEPowerManager電源相關服務
ALARM_SERVICEAlarmManager鬧鐘與定時任務
NOTIFICATION_SERVICENotificationManager狀態列通知
KEYGUARD_SERVICEKeyguardManager鍵盤鎖/螢幕鎖
LOCATION_SERVICELocationManager定位服務,如 GPS
SEARCH_SERVICESearchManager搜尋服務
VIBRATOR_SERVICEVibrator手機震動
CONNECTIVITY_SERVICEConnectivityManager網路連線狀態
WIFI_SERVICEWifiManagerWi-Fi 管理
TELEPHONY_SERVICETelephonyManager電話相關服務
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved