前幾天在通過LayoutInflater
渲染出子布局欠痴,并添加進(jìn)入父容器的時候,出現(xiàn)了子布局的寬高屬性不生效的情況,為此肌幽,總結(jié)一下和LayoutInflater
相關(guān)的知識。
一抓半、獲得LayoutInflater
在Android
當(dāng)中喂急,如果想要獲得LayoutInflater
實例,一共有以下3種方法:
1.1 LayoutInflater inflater = getLayoutInflater();
這種在Activity
里面使用笛求,它其實是調(diào)用了
/**
* Convenience for calling
* {@link android.view.Window#getLayoutInflater}.
*/
@NonNull
public LayoutInflater getLayoutInflater() {
return getWindow().getLayoutInflater();
}
下面我們再來看一下Window
的實現(xiàn)類PhoneWindow.java
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
它其實就是在構(gòu)造函數(shù)中調(diào)用了下面1.2
的方法廊移。
而如果是調(diào)用了Fragment
中也有和其同名的方法,但是是隱藏的探入,它的理由是:
/**
* @hide Hack so that DialogFragment can make its Dialog before creating
* its views, and the view construction can use the dialog's context for
* inflation. Maybe this should become a public API. Note sure.
*/
public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
final LayoutInflater result = mHost.onGetLayoutInflater();
if (mHost.onUseFragmentManagerInflaterFactory()) {
getChildFragmentManager(); // Init if needed; use raw implementation below.
result.setPrivateFactory(mChildFragmentManager.getLayoutInflaterFactory());
}
return result;
}
1.2 LayoutInflater inflater = LayoutInflater.from(this);
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}
可以看到狡孔,它其實是調(diào)用了1.3
,但是加上了判空處理蜂嗽,也就是說我們從1.1
當(dāng)中的Activity
和1.2
方法中獲取的LayoutInflater
不可能為空苗膝。
1.3 LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
這三種實現(xiàn),默認(rèn)最終都是調(diào)用了最后一種方式植旧。
二辱揭、LayoutInflater#inflate
其inflater
一共有四個重載方法,最終都是調(diào)用了最后一種實現(xiàn)病附。
2.1 (@LayoutRes int resource, @Nullable ViewGroup root)
/**
* Inflate a new view hierarchy from the specified xml resource. Throws
* {@link InflateException} if there is an error.
*
* @param resource ID for an XML layout resource to load (e.g.,
* <code>R.layout.main_page</code>)
* @param root Optional view to be the parent of the generated hierarchy.
* @return The root View of the inflated hierarchy. If root was supplied,
* this is the root View; otherwise it is the root of the inflated
* XML file.
*/
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
該方法问窃,接收兩個參數(shù),一個是需要加載的xml
文件的id
完沪,一個是該xml
需要添加的布局域庇,根據(jù)root
的情況,返回值分為兩種:
- 如果
root == null
,那么返回這個root
- 如果
root != null
较剃,那么返回傳入xml
的根View
2.2 (XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
/**
* Inflate a new view hierarchy from the specified xml node. Throws
* {@link InflateException} if there is an error. *
* <p>
* <em><strong>Important</strong></em> For performance
* reasons, view inflation relies heavily on pre-processing of XML files
* that is done at build time. Therefore, it is not currently possible to
* use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
*
* @param parser XML dom node containing the description of the view
* hierarchy.
* @param root Optional view to be the parent of the generated hierarchy.
* @return The root View of the inflated hierarchy. If root was supplied,
* this is the root View; otherwise it is the root of the inflated
* XML file.
*/
public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
return inflate(parser, root, root != null);
}
它的返回值情況和2.1
類似咕别,不過它提供的是不是xml
的id
,而是XmlPullParser
写穴,但是由于View
的渲染依賴于xml
在編譯時的預(yù)處理惰拱,因此,這個方法并不合適啊送。
2.3 public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
/**
* Inflate a new view hierarchy from the specified xml resource. Throws
* {@link InflateException} if there is an error.
*
* @param resource ID for an XML layout resource to load (e.g.,
* <code>R.layout.main_page</code>)
* @param root Optional view to be the parent of the generated hierarchy (if
* <em>attachToRoot</em> is true), or else simply an object that
* provides a set of LayoutParams values for root of the returned
* hierarchy (if <em>attachToRoot</em> is false.)
* @param attachToRoot Whether the inflated hierarchy should be attached to
* the root parameter? If false, root is only used to create the
* correct subclass of LayoutParams for the root view in the XML.
* @return The root View of the inflated hierarchy. If root was supplied and
* attachToRoot is true, this is root; otherwise it is the root of
* the inflated XML file.
*/
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
如果我們需要渲染的xml
是id
類型的偿短,那么會先把它解析為XmlResourceParser
,然后調(diào)用2.4
的方法馋没。
2.4 public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
/**
* Inflate a new view hierarchy from the specified XML node. Throws
* {@link InflateException} if there is an error.
* <p>
* <em><strong>Important</strong></em> For performance
* reasons, view inflation relies heavily on pre-processing of XML files
* that is done at build time. Therefore, it is not currently possible to
* use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
*
* @param parser XML dom node containing the description of the view
* hierarchy.
* @param root Optional view to be the parent of the generated hierarchy (if
* <em>attachToRoot</em> is true), or else simply an object that
* provides a set of LayoutParams values for root of the returned
* hierarchy (if <em>attachToRoot</em> is false.)
* @param attachToRoot Whether the inflated hierarchy should be attached to
* the root parameter? If false, root is only used to create the
* correct subclass of LayoutParams for the root view in the XML.
* @return The root View of the inflated hierarchy. If root was supplied and
* attachToRoot is true, this is root; otherwise it is the root of
* the inflated XML file.
*/
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
View result = root;
try {.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
//1.如果根節(jié)點的元素不是START_TAG昔逗,那么拋出異常。
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
//2.如果根節(jié)點的標(biāo)簽是<merge>篷朵,那么必須要提供一個root勾怒,并且該root要被作為xml的父容器。
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
//2.1遞歸地調(diào)用它所有的孩子.
rInflate(parser, root, inflaterContext, attrs, false);
} else {
//temp表示傳入的xml的根View
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
//如果提供了root并且不需要把xml的布局加入到其中声旺,那么僅僅需要給它設(shè)置參數(shù)就好笔链。
//如果提供了root并且需要加入,那么不會設(shè)置參數(shù)腮猖,而是調(diào)用addView方法鉴扫。
if (root != null) {
//如果提供了root,那么產(chǎn)生參數(shù)澈缺。
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
//遞歸地遍歷孩子.
rInflateChildren(parser, temp, attrs, true);
if (root != null && attachToRoot) {
//addView時需要加上前面產(chǎn)生的參數(shù)坪创。
root.addView(temp, params);
}
//如果沒有提供root,或者即使提供root但是不用將root作為parent姐赡,那么返回的是渲染的xml莱预,在`root != null && attachToRoot`時,才會返回root项滑。
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (Exception e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
return result;
}
}
我們簡單總結(jié)一下英文注釋當(dāng)中的說明依沮,具體的流程可以看上面的中文注釋。
- 作用:從特定的
xml
節(jié)點渲染出一個新的view
層級杖们。 - 提示:為了性能考慮,不應(yīng)當(dāng)在運行時使用
XmlPullParser
來渲染布局肩狂。 - 參數(shù)
parser
:包含有描述xml
布局層級的parser xml dom
摘完。 - 參數(shù)
root
,可以是渲染的xml
的parent
(attachToRoot == true
)傻谁,或者僅僅是為了給渲染的xml
層級提供LayoutParams
孝治。 - 參數(shù)
attachToRoot
:渲染的View
層級是否被添加到root
中,如果不是,那么僅僅為xml
的根布局生成正確的LayoutParams
谈飒。 - 返回值:如果
attachToRoot
為真岂座,那么返回root
,否則返回渲染的xml
的根布局杭措。
三费什、不指定root的情況
由前面的分析可知,當(dāng)我們沒有傳入root
的時候手素,LayoutInflater
不會調(diào)用temp.setLayoutParams(params)
鸳址,也就是像之前我遇到問題時的使用方式一樣:
LinearLayout linearLayout = (LinearLayout) mLayoutInflater.inflate(R.layout.linear_layout, null);
mContentGroup.addView(linearLayout);
當(dāng)沒有調(diào)用上面的方法時,linearLayout
內(nèi)部的mLayoutParams
參數(shù)是沒有被賦值的泉懦,下面我們再來看一下稿黍,通過這個返回的temp
參數(shù),把它通過不帶參數(shù)的addView
方法添加進(jìn)去崩哩,會發(fā)生什么巡球。
調(diào)用addView
后,如果沒有指定index
邓嘹,那么會把index
設(shè)為-1
酣栈,按前面的分析,那么下面這段邏輯中的getLayoutParams()
必然是返回空的吴超。
public void addView(View child, int index) {
if (child == null) {
throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
}
LayoutParams params = child.getLayoutParams();
if (params == null) {
params = generateDefaultLayoutParams();
if (params == null) {
throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
}
}
addView(child, index, params);
}
在此情況下钉嘹,為它提供了默認(rèn)的參數(shù),那么鲸阻,這個默認(rèn)的參數(shù)是什么呢跋涣?
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
也就是說,當(dāng)我們通過上面的方法得到一個View
樹之后鸟悴,將它添加到某個布局中陈辱,這個View
數(shù)所指定的根布局中的寬高屬性其實是不生效的,而是變?yōu)榱?code>LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT细诸。