1. LayoutInflater是做什么的
Instantiates a layout XML file into its corresponding {@link android.view.View}objects.
實(shí)例化一個(gè)布局XML文件轉(zhuǎn)換為相應(yīng)的{ @link android.view。視圖對象};
在Android開發(fā)中LayoutInflater經(jīng)常要用到,F(xiàn)ragment睡互,adapter中的視圖都是需要LayoutInflater將XML文件轉(zhuǎn)換為View對象
2. 獲取LayoutInflater對象
獲取LayoutInflater對象有三種方法
(1)getLayoutInflater()
調(diào)用Activity的getLayoutInflater()
(2)LayoutInflater.from(context)
調(diào)用LayoutInflater的靜態(tài)方法從context中獲取LayoutInflater對象
(3)(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
調(diào)用系統(tǒng)服務(wù)獲取LayoutInflater對象
3.將XML文件轉(zhuǎn)換為View對象
最常用的做法
View view = layoutinflater.inflate(R.layout.XXX,null);
到此為止享甸,上述的方法基本能實(shí)現(xiàn)布局從xml轉(zhuǎn)換為想要的View對象
但是前幾天在做RecyclerView的時(shí)候發(fā)現(xiàn)一個(gè)問題族壳,如下
4.RecyclerView中item設(shè)置寬高無效
item_recyclerview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:padding="20dp"
android:background="#44ff0000">
<TextView
android:id="@+id/tv_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#ffffff"
android:textSize="26sp"/>
</RelativeLayout>
recyclerview的adapter中布局轉(zhuǎn)換
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = lif.inflate(R.layout.item_recyclerview,null);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
簡單的item布局徒溪,實(shí)現(xiàn)的效果如下
發(fā)現(xiàn)明明設(shè)置了寬度是match_parent,顯示出來的效果確實(shí)有點(diǎn)像wrap_content
然后調(diào)整item的高度金顿,發(fā)現(xiàn)也是不起作用的
在檢查代碼之后找不到出現(xiàn)問題的原因臊泌,百度了一波找到原因
※在布局轉(zhuǎn)換的時(shí)候使用
View view = layoutinflater.inflate(R.layout.item_XXX,ViewGroup,false);
修改之后,效果如下
符合預(yù)期效果揍拆。
※問題:
(1)為什么使用三個(gè)參數(shù)的inflate方法就能實(shí)現(xiàn)效果渠概?
(2)inflate三個(gè)參數(shù)和兩個(gè)參數(shù)有什么區(qū)別?
5.LayoutInflater.inflate方法分析
inflate有重載4個(gè)方法
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root)
public View inflate(XmlPullParser parser, @Nullable ViewGroup root)
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
查看源碼發(fā)現(xiàn)不管是三個(gè)參數(shù)還是兩個(gè)參數(shù)的inflate方法
最終是實(shí)現(xiàn)了
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
attachToRoot的值是根據(jù) root != null來賦值
/**
* 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) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
View result = root;
try {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
if (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
}
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");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp against its context.
rInflateChildren(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
final InflateException ie = new InflateException(e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(parser.getPositionDescription()
+ ": " + e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return result;
}
}
(1)第一個(gè)參數(shù)parser
parser:xml文件
如果傳入的是layout的id嫂拴,會調(diào)用
final XmlResourceParser parser = res.getLayout(resource)播揪;轉(zhuǎn)換成xml文件
(2)第二個(gè)參數(shù)root,第三個(gè)參數(shù)attachToRoot
- root不為空
和第三個(gè)參數(shù)attachToRoot有關(guān)
① 如果attachToRoot為true
root成為inflate出來的view對象的父布局
② 如果attachToRoot為false
inflate出來的view的根布局提供LayoutParams參數(shù)的控件
final AttributeSet attrs = Xml.asAttributeSet(parser);
....
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
當(dāng)root不為空筒狠,attachToRoot為false時(shí)候猪狈。
獲得xml文件中的屬性
通過createViewFromTag生成View
再通過generateLayoutParams(attrs)生成layoutparams參數(shù)
設(shè)置到view中,使得view有l(wèi)ayoutParams
- root為空(null)
※不指定父布局辩恼,那么inflate出來的view對象的根布局的某些參數(shù)會失效雇庙,比如Layout_width和Layout_height會失效
6.寫后感
源碼封裝的太好了,代碼跳來跳去灶伊,對于不經(jīng)辰埃看源碼的我來說很容易看不下去。不過還是硬著頭皮慢慢看下去聘萨,不要往深層去看竹椒,有些可以選擇性忽略,只要看懂注釋大概懂得米辐,等知識累積的更多了相信再去重新解讀源碼會有新收獲胸完。