在實際工作中,事先寫好的佈局文件往往不能滿足我們的需求,有時會根據情況在代碼中自定義控件,這就需要用到LayoutInflater。
LayoutInflater在Android中是“擴展”的意思,作用類似於findViewById(),不同的是LayoutInflater是用來獲得佈局文件對象的,而
findViewById()是用來獲得具體控件的。LayoutInflater經常在BaseAdapter的getView方法中用到,用來獲取整個View並返回。
LayoutInflater的用法有三種:
第一種方法:
- LayoutInflater inflater = LayoutInflater.from(this);
- View layout = inflater.inflate(R.layout.main, null);
第二種方法:
- 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);
第一種方法的本質就是調用第三種方法,而第二種方法和第三種方法有什麼區別,我還真不知道,有哪位知道的請留言指教啊!
下面是簡單的使用示例:
- public class LayoutInflaterActivity extends Activity {
- private EditText et;
- private Button btn;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // 第一種方法
- LayoutInflater inflater = LayoutInflater.from(this);
- View layout = inflater.inflate(R.layout.main, null);
- // 第二種方法
- // 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);
- }
- }
另外補充下,getSystemService是Activity中的方法,根據傳入的name來取得對應的服務對象,這些服務名稱參數都是Context類中的常量:
傳入的Name 返回的對象 說明
WINDOW_SERVICE WindowManager 管理打開的窗口程序
LAYOUT_INFLATER_SERVICE LayoutInflater 取得xml裏定義的view
ACTIVITY_SERVICE ActivityManager 管理應用程序的系統狀態
POWER_SERVICE PowerManger 電源的服務
ALARM_SERVICE AlarmManager 鬧鐘的服務
NOTIFICATION_SERVICE NotificationManager 狀態欄的服務
KEYGUARD_SERVICE KeyguardManager 鍵盤鎖的服務
LOCATION_SERVICE LocationManager 位置的服務,如GPS
SEARCH_SERVICE SearchManager 搜索的服務
VEBRATOR_SERVICE Vebrator 手機震動的服務
CONNECTIVITY_SERVICE Connectivity 網絡連接的服務
WIFI_SERVICE WifiManager Wi-Fi服務
TELEPHONY_SERVICE TeleponyManager 電話服務