获取LayoutInflater
获取LayoutInflater的方法也有三种
LayoutInflater inflater1 = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)
LayoutInflater inflater2 = LayoutInflater.from(this);
LayoutInflater inflater3 = getLayoutInflater();
LayoutInflater的解析过程
LayoutInflater可以将xml的布局文件解析为view,它是一个抽象类,实现类是PhoneLayoutInflater。LayoutInflater会遍历View树,然后根据View的全路径名利用反射获取构造器,从而实现View实例。PhoneLayoutInflater实现了onCreateView()方法,当调用LayoutInflater的inflate()时,最终就会调用onCreateView(),从而创建出view
解析的过程分为三步:
- 获取XmlResourceParse
- 解析View树
- 解析View
1. 获取XmlResourceParser
当获取了LayoutInflater后,会通过inflater()方法进行调度,这个方法也是最常用的方法
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
inflate方法中的三个参数分别为
- int resource
传入即将解析的xml文件,例如R.layout.activity_main - boolean attachToRoot
用于表示是否要添加到父布局root中 - ViewGroup root
root参数比较关键,虽然有时我们会传入null值。root和attachToRoot参数结合使用 (1)root != null时 当attachToRoot == true新解析出来的View会被add到root中去,然后将root作为结果返回。 当attachToRoot == false时,新解析的View会直接作为结果返回,而且root会为新解析的View生成LayoutParams并设置到该View中去。 (2) root == null时 attachToRoot == false,新解析的View会直接作为结果返回。例如root为null时,新解析出来的View没有LayoutParams参数,这时候设置layout_width和layout_height是不生效的。
inflate方法的源码如下
public abstract class LayoutInflater {
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();
}
}
}
从上述代码可以看到,Resources中的getLayout()方法比较关键,该方法调用了Resources的loadXmlResourceParser() 方法来完成XmlResourceParser的加载,如下所示:
public class Resources {
XmlResourceParser loadXmlResourceParser(@AnyRes int id, @NonNull String type)
throws NotFoundException {
final TypedValue value = obtainTempTypedValue();
try {
final ResourcesImpl impl = mResourcesImpl;
impl.getValue(id, value, true);
if (value.type == TypedValue.TYPE_STRING) {
return impl.loadXmlResourceParser(value.string.toString(), id,
value.assetCookie, type);
}
throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
+ " type #0x" + Integer.toHexString(value.type) + " is not valid");
} finally {
releaseTempTypedValue(value);
}
}
}
其中关键的方法是impl.loadXmlResourceParser(value.string.toString(), id, value.assetCookie, type),用来加载对应的loadXmlResourceParser解析器,源码如下
public class ResourcesImpl {
loadXmlResourceParser(@NonNull String file, @AnyRes int id, int assetCookie,
@NonNull String type)
throws NotFoundException {
if (id != 0) {
try {
synchronized (mCachedXmlBlocks) {
final XmlBlock block = mAssets.openXmlBlockAsset(assetCookie, file);
if (block != null) {
final int pos = (mLastCachedXmlBlockIndex + 1) % num;
mLastCachedXmlBlockIndex = pos;
final XmlBlock oldBlock = cachedXmlBlocks[pos];
if (oldBlock != null) {
oldBlock.close();
}
cachedXmlBlockCookies[pos] = assetCookie;
cachedXmlBlockFiles[pos] = file;
cachedXmlBlocks[pos] = block;
return block.newParser();
}
}
} catch (Exception e) {
final NotFoundException rnf = new NotFoundException("File " + file
+ " from xml type " + type + " resource ID #0x" + Integer.toHexString(id));
rnf.initCause(e);
throw rnf;
}
}
throw new NotFoundException("File " + file + " from xml type " + type + " resource ID #0x"
+ Integer.toHexString(id));
}
}
其中,四个关键的形参为 我们先来看看这个方法的四个形参:
- String file:xml文件的路径
- int id:xml文件的资源ID
- int assetCookie:xml文件的资源缓存
- String type:资源类型
通过openXmlBlockAsset()方法创建新的XmlBlock
public final class AssetManager implements AutoCloseable {
final XmlBlock openXmlBlockAsset(int cookie, String fileName)
throws IOException {
synchronized (this) {
long xmlBlock = openXmlAssetNative(cookie, fileName);
if (xmlBlock != 0) {
XmlBlock res = new XmlBlock(this, xmlBlock);
incRefsLocked(res.hashCode());
return res;
}
}
}
}
上述过程可表示如下
2. 解析View树
inflate中解析View树
- 获取根元素root(形参)
- 获取元素名name
- 如果name是merge标签,则将所以子View都添加到root中rInflate(parser, root, inflaterContext, attrs, false);
- 如果不是merge标签,调用**createViewFromTag()**方法解析成布局中的视图temp(View类型),再根据attachToRoot决定是否添加到root中
- 调用rInflateChildren()方法解析当前View下面的所有子View
public abstract class LayoutInflater {
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 {
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 (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 {
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);
}
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
rInflateChildren(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
if (root != null && attachToRoot) {
root.addView(temp, params);
}
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 {
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return result;
}
}
}
其中重要的方法是rInflate,上述代码中有使用到 rInflate(parser, root, inflaterContext, attrs, false) ,rInflate和rInflateChildren的源码如下:
- 获取树的深度depth,执行深度优先遍历
- 逐个元素进行解析,先通过parser.getName()得到元素名,然后匹配name是否为request_focus、Tag、include、merge等标签,做相应处理,如果都不是开始根据元素名进行解析
- 先根据元素名生成View
final View view = createViewFromTag(parent, name, context, attrs); - 生成相应的LayoutParams:
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs); - 递归生成子View:
rInflateChildren(parser, view, attrs, true); - 将解析出来的View添加到它的父View中
viewGroup.addView(view, params) - 最后回调根容器的
parent.onFinishInflate();
public abstract class LayoutInflater {
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
}
rInflaterChildren方法
LayoutInflater.java
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
3.解析View
- 如果标签与主题相关,则需要将context与themeResId包裹成ContextThemeWrapper。
- 通过
view = onCreateView(parent, name, attrs) 对内置View, view = createView(name, null, attrs) 解析自定义View
public abstract class LayoutInflater {
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
if (!ignoreThemeAttr) {
final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
}
if (name.equals(TAG_1995)) {
return new BlinkLayout(context, attrs);
}
try {
View view;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
}
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name, e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name, e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
}
}
}
onCreateView在PhoneLayoutInflater被实现,主要就是给内置View加下面三种前缀
public class PhoneLayoutInflater extends LayoutInflater {
private static final String[] sClassPrefixList = {
"android.widget.",
"android.webkit.",
"android.app."
};
@Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
for (String prefix : sClassPrefixList) {
try {
View view = createView(name, prefix, attrs);
if (view != null) {
return view;
}
} catch (ClassNotFoundException e) {
}
}
return super.onCreateView(name, attrs);
}
}
真正构建View还是createView方法完成的,根据完整的类的路径名利用反射机制构建View对象
public abstract class LayoutInflater {
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Constructor<? extends View> constructor = sConstructorMap.get(name);
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(name);
}
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
if (constructor == null) {
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);
} else {
if (mFilter != null) {
Boolean allowedState = mFilterMap.get(name);
if (allowedState == null) {
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
}
Object[] args = mConstructorArgs;
args[1] = attrs;
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;
} catch (NoSuchMethodException e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + (prefix != null ? (prefix + name) : name), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (ClassCastException e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Class is not a View " + (prefix != null ? (prefix + name) : name), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (ClassNotFoundException e) {
throw e;
} catch (Exception e) {
final InflateException ie = new InflateException(
attrs.getPositionDescription() + ": Error inflating class "
+ (clazz == null ? "<unknown>" : clazz.getName()), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
}
LayoutParams
LayoutParams 的作用是用于子View的布局,是ViewGroup的一个内部抽象类,封装了Layout的位置、高、宽等信息,常用子类的简单使用:LinearLayout.LayoutParams、RelativeLayout.Params以及WindowManager.Params。
TextView textView = new TextView(context);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200);
layoutParams.width=100;
layoutParams.height=200;
textView.setLayoutParams(layoutParams);
如果textview外围包围着LinearLayout
LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) textView.getLayoutParams();
layoutParams1.weight=1;
layoutParams1.topMargin=5;
layoutParams1.setMarginEnd(20);
layoutParams1.setMargins(3,3,3,3);
RelativeLayout
RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) textView.getLayoutParams();
layoutParams1.addRule(RelativeLayout.CENTER_IN_PARENT);
layoutParams1.addRule(RelativeLayout.RIGHT_OF, R.id.all);
layoutParams1.topMargin=5;
layoutParams1.setMarginEnd(20);
layoutParams1.setMargins(3,3,3,3);
layoutParams1.removeRule(RelativeLayout.CENTER_IN_PARENT);
FrameLayout
FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) textView.getLayoutParams();
layoutParams1.gravity = Gravity.CENTER;
layoutParams1.topMargin = 5;
layoutParams1.setMarginEnd(20);
layoutParams1.setMargins(3, 3, 3, 3);
例子1:动态添加Button
布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="我是xml文件加载的布局"/>
</RelativeLayout>
方法一:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button btnOne = new Button(this);
btnOne.setText("我是动态添加的按钮");
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.CENTER_IN_PARENT);
setContentView(R.layout.activity_main);
RelativeLayout rly = (RelativeLayout) findViewById(R.id.RelativeLayout1);
rly.addView(btnOne,lp2);
}
}
方法二:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button btnOne = new Button(this);
btnOne.setText("我是动态添加的按钮");
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.CENTER_IN_PARENT);
LayoutInflater inflater = LayoutInflater.from(this);
RelativeLayout rly = (RelativeLayout) inflater
.inflate(R.layout.activity_main, null)
.findViewById(R.id.RelativeLayout1);
rly.addView(btnOne,lp2);
setContentView(rly);
}
}
例子2 添加各种Button
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.androidstudy.R;
public class AddViewActivity extends AppCompatActivity {
LinearLayout llAddView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addview);
llAddView = findViewById(R.id.ll_addview);
addSimpleButton();
addWrapButton();
addWrapReButton();
addFixButton();
addLinearCenterButton();
addRelativeCenterButton();
modifyButtonText();
}
@SuppressLint("SetTextI18n")
private void addSimpleButton(){
Button btnSimple = new Button(this);
btnSimple.setText("最简单的直接添加");
llAddView.addView(btnSimple);
}
@SuppressLint("SetTextI18n")
private void addWrapButton(){
Button btnWrap = new Button(this);
btnWrap.setText("WRAP_CONTENT");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
llAddView.addView(btnWrap,params);
}
@SuppressLint("SetTextI18n")
private void addWrapReButton(){
Button btnWrap = new Button(this);
btnWrap.setText("RELATIVE_WRAP_CONTENT");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
llAddView.addView(btnWrap,params);
}
@SuppressLint("SetTextI18n")
private void addFixButton(){
Button btnFix = new Button(this);
btnFix.setText("100dp,100dp");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
new ViewGroup.LayoutParams(
(int) dipToPx(this, 100f),
(int) dipToPx(this, 100f))
);
llAddView.addView(btnFix,params);
}
@SuppressLint("SetTextI18n")
private void addLinearCenterButton(){
Button btnFix = new Button(this);
btnFix.setText("LinearCenter");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
new ViewGroup.LayoutParams((int) dipToPx(this, 300f),500)
);
params.gravity = Gravity.CENTER;
llAddView.addView(btnFix,params);
}
@SuppressLint("SetTextI18n")
private void addRelativeCenterButton(){
Button btnOne = new Button(this);
btnOne.setText("RelativeCenter");
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.CENTER_IN_PARENT);
RelativeLayout rly = (RelativeLayout) findViewById(R.id.rr_addview);
rly.addView(btnOne,lp2);
}
private void modifyButtonText(){
Button btnModifyText = findViewById(R.id.btn_native);
btnModifyText.setText("Modify");
}
private float dipToPx(Context context, float dip) {
return dip * getDeviceDensity(context) + 0.5f;
}
private float getDeviceDensity(Context context) {
return context.getResources().getDisplayMetrics().density;
}
private float pxToDip(Context context, float px) {
return px / getDeviceDensity(context) + 0.5f;
}
}
参考博客地址
|