Android加载View一般有两种方式,第一种方式就是在Activity中直接使用setContentView()方法来加载,第二种方式则是使用LayoutInflater的inflate方法来映射View。
1、先看在Activity中的setContentView()方法。
点击查看源码,可看出它是定义在AppCompatDelegate类当中的(注:activity是基于AppCompatActivity)。
@Override
public void setContentView(@LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
@Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
而AppCompatDelegate是一个abstract类,查找其实现类,在它里面一个静态的create方法:
private static AppCompatDelegate create(Context context, Window window,
AppCompatCallback callback) {
final int sdk = Build.VERSION.SDK_INT;
if (sdk >= 23) {
return new AppCompatDelegateImplV23(context, window, callback);
} else if (sdk >= 14) {
return new AppCompatDelegateImplV14(context, window, callback);
} else if (sdk >= 11) {
return new AppCompatDelegateImplV11(context, window, callback);
} else {
return new AppCompatDelegateImplV7(context, window, callback);
}
}
这个方法根据不同的SDK返回了不同的实现类,因为仅仅是为兼容问题,所以我们随便打开一个,就打开AppCompatDelegateImplV7,通过查找可以发现如果下代码来实现setContentView()方法:
@Override
public void setContentView(View v) {
ensureSubDecor();
ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
contentParent.removeAllViews();
contentParent.addView(v);
mOriginalWindowCallback.onContentChanged();
}
@Override
public void setContentView(int resId) {
ensureSubDecor();
ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
contentParent.removeAllViews();
LayoutInflater.from(mContext).inflate(resId, contentParent);
mOriginalWindowCallback.onContentChanged();
}
@Override
public void setContentView(View v, ViewGroup.LayoutParams lp) {
ensureSubDecor();
ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
contentParent.removeAllViews();
contentParent.addView(v, lp);
mOriginalWindowCallback.onContentChanged();
}
看到这里,我想大家就明白了,我们来看第二个重载方法,setContentView(int resId)方法,里面有一句
LayoutInflater.from(mContext).inflate(resId, contentParent);
看到这里就恍然大悟了,原来setContentView(R.layout.id),也是调用LayoutInflater.inflate()方法来实现的。
2、接下来再来看LayoutInflater.infalte()方法
LayoutInflater.inflate有四个重载方法,分别是:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
return inflate(parser, root, root != null);
}
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();
}
}
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) {
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;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
}
通过上面四个方法的分析,前面三个方法最终调用的都是第四个方法里面,现在着重来看一下第四个方法,我们以例子的形式来分析代码。
先将需要的代码引入,代码很简单,一个MainActivity类
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = LayoutInflater.from(this);
// LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
// View view = inflater.inflate(R.layout.activity_main, null);
// view = inflater.inflate(R.layout.test, (ViewGroup) view, false);
View view = inflater.inflate(R.layout.test, null);
setContentView(view);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#00ff00">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:textSize="25sp"
android:text="main" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#ff0000"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="25sp"
android:gravity="center"
android:text="test" />
</LinearLayout>
1、我们经常会这种使用:
View view = inflater.inflate(R.layout.test, null);
先来看一下最终执行的结果
if (root == null || !attachToRoot) {
result = temp;
}
通过这句代码可以看出最终返回的就是layoutResourceId对应的layout,所以直接返回的是test.xml生成的样式,这里会出一个疑问test.xml本身设置了200dp,这里为什么会全屏显示呢?其实这样想,layout_width和layout_height属性都是针对于父View存在的,那么现在父View都不存在了,layout_width和layout_height属性设置什么值,也就没有意义了,所以最终会显示一个全屏的test.xml生成的View。
我们把MainActivity改成这样(ViewGroup传进去一个父类,并且attach参数设为false):
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = LayoutInflater.from(this);
// LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_main, null);
view = inflater.inflate(R.layout.test, (ViewGroup) view, false);
// View view = inflater.inflate(R.layout.test, null);
setContentView(view);
}
}
先看一下这种写法的实现效果:
这种写法可以说是按我们的要求把test.xml显示出来,test.xml的root layout的各种属性也正常了,下面我们来分析一下,为什么test.xml的属性会起作用?首先看代码:
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);
}
}
这段代码的意思,如果root不为空,那么就生成一个LayoutParams 然后将LayoutParams设置给temp(也就是通过text.xml生成的view),这样test.xml的属性就起作用了,又因为attach为false所以最终会执行:
if (root == null || !attachToRoot) {
result = temp;
}
这句代码执行完毕就出现了上图呈现的效果。
我们把MainActivity的代码再改成这样:
执行后的效果为:
这样的结果 ,既把root完整显示,并且把layoutResourceId所以指向的View按格式显示出来了。我们来看这句代码:
if (root != null && attachToRoot) {
root.addView(temp, params);
}
因为不root不等于空,所以会把temp加进root并显示。
至此对LayoutInflater的理解基本上就是这些了,如果有什么不对的地方,敬请理解并告知。