將布局文件/res/layout/my_view.xml實(shí)例化為View對象,inflate()方法返回布局文件的view對象。
LayoutInflater.from(getContext()).inflate(int resource,ViewGroup root);//root為null,不把view添加到root中;root非空則添加。
LayoutInflater.from(getContext()).inflate(int resource,ViewGroup root,boolean attachToRoot);//root非空,attachToRoot為true,才把view添加到root中。
區(qū)別
因?yàn)閂iew.inflate(context,layoutResId,root) 比 LayoutInflater.from(context).inflate(layoutResId, root, attachToRoot) 少了一個(gè)attachToRoot參數(shù)(是否將layoutResId添加到某個(gè)View中,作為其子View)。
在使用View.inflate(context,layoutResId,root) 時(shí),如果root(父View)是null,會導(dǎo)致layoutResId布局中聲明的寬高 + 外邊距參數(shù),失效。
核心條件就是root(父View)是不是null。
1、使用View.inflate(context,layoutResId,root) root不為null
2、使用LayoutInflater.from(context).inflate(layoutResId, root, attachToRoot) root不為null,且attachToRoot是true
結(jié)果:兩種方式效果相同,寬高 + 外邊距 都有效
3、使用View.inflate(context,layoutResId,root) root為 null
4、使用LayoutInflater.from(context).inflate(layoutResId, root, attachToRoot) root為 null,且attachToRoot是false
兩種方式效果相同,寬高 + 外邊距 都失效了,寬/高 變成wrap_content,一點(diǎn)要記住這點(diǎn)!!!是變成wrap_content。
至于為什么layoutResId布局寬度和父View一樣,當(dāng)子View失去自身LayoutParams(布局參數(shù))后,父View會自動調(diào)整子View的寬高屬性,下面會講,先忽略。
5、如果不想將layoutResId布局添加到父View中,同時(shí)又不想丟失layoutResId布局中聲明的參數(shù),
LayoutInflater.from(context).inflate(layoutResId, root, attachToRoot)這樣寫可以做到,root不為null,但是attachToRoot為false。
6、而View.inflate(context,layoutResId,root) 目前為止無法做到,因?yàn)樗倭艘粋€(gè)attachToRoot參數(shù)(是否將layoutResId添加到某個(gè)View中,作為其子View)。
父View自動調(diào)整子View的寬高
當(dāng)子View 沒有 或 失去 自身LayoutParams(布局參數(shù))后,父View會自動調(diào)整子View的寬高。
布局類型不同,子View寬高值也不同,說幾個(gè)常用布局:
FrameLayout:寬 / 高 都會變成match_parent
RelativeLayout 和 ConstraintLayout 一樣,寬 / 高 都會變成wrap_content
LinearLayout 設(shè)置vertical(垂直方向):寬變成match_parent,高變成wrap_content
LinearLayout 設(shè)置horizontal(水平方向):寬 / 高 都會變成wrap_content
layoutResId布局作為子View時(shí),返回的是父布局View,反之返回的是layoutResId布局View。
來源:https://blog.csdn.net/Lan_Se_Tian_Ma/article/details/134819765
http://www.rzrgm.cn/baipengzhan/p/LayoutInflater_inflate_View_inflate.html
浙公網(wǎng)安備 33010602011771號