android LayoutInflater
稍微学习了android的绘制机制,就来了解了一下android的LayoutInflater,字面意思就是布局填充,根据指定的xml布局加载布局,返回一个view。
- 想要使用它首先要获取 LayoutInflater的实例化对象
可以通过下面两种方式获取
LayoutInflater layoutInflater = LayoutInflater.from(context);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
后面就可以调用里面的inflate方法加载布局
layoutInflater.inflate(resourceId, root);
- 其实以前一直不能理解为什么xml文件和java文件能够联系起来,附上源码
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
final AttributeSet attrs = Xml.asAttributeSet(parser);
mConstructorArgs[0] = mContext;
View result = root;
try {
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
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, attrs);
} else {
View temp = createViewFromTag(name, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
rInflate(parser, temp, attrs);
if (root != null && attachToRoot) {
root.addView(temp, params);
}
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (IOException e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
}
return result;
}
}
可以发现,这里面对xml进行了pull解析,通过获取了xml中的内容进行操作,通过createViewFromTag(name, attrs)方法进行view的获取同时将成员添加入viewGroup中,同时通过rInflate(parser, root, attrs)遍历子view同时将其添加进入viewGroup,从而达到了加载布局的作用,并返回view实例,便于调用。