Android LayoutInflater,layoutinflater
作用:
類似於findViewById()
不同點是LayoutInflater是用來找res/layout/下的xml布局檔案,並且執行個體化;
而findViewById()是找xml布局檔案下的具體widget控制項(如Button、TextView等)
具體作用:1、對於一個沒有被載入或者想要動態載入的介面,都需要使用LayoutInflater.inflate()來載入;2、對於一個已經載入的介面,就可以使用Activiyt.findViewById()方法來獲得其中的介面元素。
使用:
LayoutInflater 是一個抽象類別,在文檔中如下聲明:public abstract class LayoutInflater extends Object獲得 LayoutInflater 執行個體的三種方式1. LayoutInflater inflater = getLayoutInflater();//調用Activity的getLayoutInflater() 2. LayoutInflater inflater = LayoutInflater.from(context); 3. LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflate 方法通過 sdk 的 api 文檔,可以知道該方法有以下幾種過載形式,返回值均是 View 對象,如下:public View inflate (int resource, ViewGroup root) public View inflate (XmlPullParser parser, ViewGroup root)public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot) public View inflate (int resource, ViewGroup root, boolean attachToRoot)示意代碼:LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.custom, (ViewGroup)findViewById(R.id.test)); //EditText editText = (EditText)findViewById(R.id.content);// error EditText editText = (EditText)view.findViewById(R.id.content);對於上面代碼,指定了第二個參數 ViewGroup root,當然你也可以設定為 null 值。
針對getSystemService()參數的種類:WINDOW_SERVICEWindowManager 管理開啟的視窗程序LAYOUT_INFLATER_SERVICELayoutInflater 取得xml裡定義的viewACTIVITY_SERVICEActivityManager 管理應用程式的系統狀態POWER_SERVICEPowerManger 電源的服務ALARM_SERVICEAlarmManager 鬧鐘的服務NOTIFICATION_SERVICENotificationManager 狀態列的服務KEYGUARD_SERVICEKeyguardManager 鍵盤鎖的服務LOCATION_SERVICELocationManager 位置的服務,如GPSSEARCH_SERVICESearchManager 搜尋的服務VEBRATOR_SERVICEVebrator 手機震動的服務CONNECTIVITY_SERVICEConnectivity 網路連接的服務WIFI_SERVICEWifiManager Wi-Fi服務TELEPHONY_SERVICETeleponyManager 電話語音
Code Demo:Context mContext = MainActivity.this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);View layout = inflater.inflate(R.layout.custom_dialog, null);TextView text = (TextView) layout.findViewById(R.id.text);text.setText("Hello, Welcome to Mr Wei's blog!");ImageView image = (ImageView) layout.findViewById(R.id.image);image.setImageResource(R.drawable.icon);
問個android的問題,學習Java的也可以吧
第一個就是建立一個LayoutInflater 的執行個體對象,通過這個應用程式的上下文(context)獲得!然後第二句話就是說你建立了一個VIEW,然後通過LayoutInflater這個執行個體對象的inflate方法,獲得一個布局檔案,這個VIEW使用的布局檔案是selectview.xml這個布局檔案,布局檔案很好理解,你平常看到的那些android手機上的介面,就是用這個xml檔案配置出來的,當然也有自訂VIEW繪製上去的!!!至於這個代碼的寫法,你要瞭解java開發就知道了
android LayoutInflater 擷取不到控制項
這個是擷取不到的,因為這個textview沒有實際被調用。但是編譯時間R檔案中確實有這個textview的id值,所以編譯什麼的都不會報錯。如果你需要擷取其中的值,就在Intent中綁定資料。或者更改它顯示內容的話,就在MainActivity中動態註冊個廣播接收器,從現在這個廣播接收器接受廣播,並改變TextView的顯示內容。