我們開發(fā)時(shí)笋妥,有時(shí)候會(huì)有動(dòng)態(tài)加載布局的需求掰烟,A情況加載一個(gè)布局伴嗡,B情況加載另一個(gè)布局急波。
下面簡(jiǎn)單介紹一下動(dòng)態(tài)布局涉及到的知識(shí)點(diǎn)以及用到的函數(shù)。
1.LayoutInflater的用法
LayoutInflater可以用來(lái)實(shí)例化 XML文件瘪校,使它成為一個(gè)View對(duì)象澄暮。
1.1 LayoutInflater實(shí)例化
? 有三種方法可以將LayoutInflater實(shí)例化:
- LayoutInflater inflater1 = LayoutInflater.from(this);
- LayoutInflater inflater2 = getLayoutInflater();
- LayoutInflater inflater3 = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
第一種寫法跟第三種寫法本質(zhì)是一樣的名段。
拿到LayoutInflater實(shí)例之后,可以調(diào)用它的inflate()方法加載布局了泣懊。
1.2 inflate()的兩種常用方法
[inflate](http://www.android-doc.com/reference/android/view/LayoutInflater.html#inflate(int, android.view.ViewGroup))(int resource,ViewGroup root)
[inflate](http://www.android-doc.com/reference/android/view/LayoutInflater.html#inflate(int, android.view.ViewGroup, boolean))(int resource,ViewGroup root, boolean attachToRoot)
第一個(gè)參數(shù)resource:ID for an XML layout resource to load (e.g., R.layout.main_page)
第二個(gè)參數(shù)root:布局的外部再嵌套一層父布局伸辟,不需要可以填null.
第三個(gè)參數(shù)attachToRoot:是否把選取的視圖加入到root中。
引用程大治的分析:
如果attachToRoot是true的話馍刮,那第一個(gè)參數(shù)的layout文件就會(huì)被填充并附加在第二個(gè)參數(shù)所指定的ViewGroup內(nèi)信夫。方法返回結(jié)合后的View,根元素是第二個(gè)參數(shù)ViewGroup卡啰。如果是false的話静稻,第一個(gè)參數(shù)所指定的layout文件會(huì)被填充并作為View返回。這個(gè)View的根元素就是layout文件的根元素匈辱。不管是true還是false振湾,都需要ViewGroup的LayoutParams來(lái)正確的測(cè)量與放置layout文件所產(chǎn)生的View對(duì)象。
1.3 舉個(gè)例子
LayoutInflater layoutInflater = LayoutInflater.from(this);
View bottom_tab = layoutInflater.inflate(R.layout.include_bottom_tab,null);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.XX);
linearLayout.addView(bottom_tab);
這樣就可以動(dòng)態(tài)地將指定的布局文件加到指定XX布局中了亡脸。
如果上述的include_bottom_tab的布局文件是類似這樣的押搪,沒有父布局:
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="30dp"
android:layout_height="80dp"
android:text="Button" >
</Button>
那么layout_xx屬性都會(huì)無(wú)效。詳見下一部分的解釋梗掰。
如果如果上述的include_bottom_tab的布局文件有父布局嵌言,那么可以直接設(shè)置布局的具體位置,如居中等及穗。
2.關(guān)于layout_XX
首先認(rèn)識(shí)一下layout_width和layout_height這個(gè)兩個(gè)屬性 。
顧名思義绵载,layout_xx 是用來(lái)設(shè)置當(dāng)前View在布局中的大小或者位置的埂陆,而不是我們默以為的設(shè)置View的大小。
同時(shí)也有人會(huì)有這樣的疑問娃豹,為什么布局最外層的布局又可以設(shè)置大小呢? 這是因?yàn)樵趕etContentView()方法中焚虱,Android會(huì)自動(dòng)在布局文件的最外層再嵌套一個(gè)FrameLayout,所以layout_width和layout_height屬性才會(huì)有效果懂版。