View_01_LayoutInflater的原理、使用方法

本篇博客是郭神博客Android视图状态及重绘流程分析,带你一步步深入了解View(一)的读书笔记的笔记。

LayoutInflater简单介绍

setContentView()内部是使用LayoutInflater来完毕载入布局的。

setContentView()方法内部的源代码是internal的。不太easy查到。

翻了七八个类后,在AppCompatDelegateImplV7.java中找到了这段代码

@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();
}

获取LayoutInflater实例

第一种方法:

     LayoutInflater layoutInflater = LayoutInflater.from(context);

另外一种方法:

     LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

事实上另外一种方法是第一种的简单写法,仅仅是Android给我们做了封装而已。

layoutInflater.inflate()方法

演示样例:

layoutInflater.inflate(resourceId, root);

第一个參数就是要载入的布局id,第二个參数是指给该布局的外部再嵌套一层父布局,假设不须要就直接传null。这样就成功成功创建了一个布局的实例。之后再将它加入到指定的位置就能够显示出来了。

实例:LayoutInflater的使用方法

activity_main.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" > </LinearLayout>

button_layout.xml

 <Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" > </Button>

如今我们要想办法,怎样通过LayoutInflater来将button_layout这个布局加入到主布局文件的LinearLayout中。依据刚刚介绍的使用方法,改动MainActivity中的代码,例如以下所看到的:

MainActivity.java

public class MainActivity extends Activity {

    private LinearLayout mainLayout;

    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout = (LinearLayout) findViewById(R.id.main_layout);
LayoutInflater layoutInflater = LayoutInflater.from(this);
View buttonLayout = layoutInflater.inflate(R.layout.button_layout, null);
mainLayout.addView(buttonLayout);
} }

结果例如以下图所看到的

LayoutInflater技术广泛应用于须要动态加入View的时候,比方在ScrollView和ListView中,常常都能够看到LayoutInflater的身影。

LayoutInflater的工作原理

inflate源代码

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;
}
}

从这里我们就能够清楚地看出,LayoutInflater事实上就是使用Android提供的pull解析方式来解析布局文件的。

这里我们注意看下第23行,调用了createViewFromTag()这种方法。并把节点名和參数传了进去。

看到这种方法名。我们就应该能猜到。它是用于依据节点名来创建View对象的。确实如此,在createViewFromTag()方法的内部又会去调用createView()方法,然后使用反射的方式创建出View的实例并返回。

当然,这里仅仅是创建出了一个根布局的实例而已。接下来会在第31行调用rInflate()方法来循环遍历这个根布局下的子元素,代码例如以下所看到的:

rInflate源代码

private void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs)
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_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
final View view = createViewFromTag(name, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflate(parser, view, attrs);
viewGroup.addView(view, params);
}
}
parent.onFinishInflate();
}

这种话。把整个布局文件都解析完毕后就形成了一个完整的DOM结构。终于会把最顶层的根布局返回,至此inflate()过程所有结束。

比較细心的朋友或许会注意到,inflate()方法还有个接收三个參数的方法重载,结构例如以下:

inflate()方法的第三个參数

inflate(int resource, ViewGroup root, boolean attachToRoot)

1. 假设root为null。attachToRoot将失去作用。设置不论什么值都没有意义。

2. 假设root不为null,attachToRoot设为true,则会给载入的布局文件的指定一个父布局,即root。

3. 假设root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被加入到父view其中时,这些layout属性会自己主动生效。

4. 在不设置attachToRoot參数的情况下,假设root不为null,attachToRoot參数默觉得true。

将上面实例中的Button按钮变大

事实上这里无论你将Button的layout_width和layout_height的值改动成多少。都不会有不论什么效果的,由于这两个值如今已经全然失去了作用。

平时我们常常使用layout_width和layout_height来设置View的大小,而且一直都能正常工作。就好像这两个属性确实是用于设置View的大小的。

而实际上则不然,它们事实上是用于设置View在布局中的大小的,也就是说,首先View必须存在于一个布局中,之后假设将layout_width设置成match_parent表示让View的宽度填充满布局,假设设置成wrap_content表示让View的宽度刚好能够包括其内容,假设设置成详细的数值则View的宽度会变成对应的数值。这也是为什么这两个属性叫作layout_width和layout_height,而不是width和height。

改动button的布局文件。不能变大

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp"
android:layout_height="80dp"
android:text="Button" >
</Button>

在button外嵌套一层布局,可使其变大

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:layout_width="300dp"
android:layout_height="80dp"
android:text="Button" >
</Button>
</RelativeLayout>

能够看到,这里我们又加入了一个RelativeLayout,此时的Button存在与RelativeLayout之中。layout_width和layout_height属性也就有作用了。

当然,处于最外层的RelativeLayout,它的layout_width和layout_height则会失去作用。如今又一次执行一下程序,结果例如以下图所看到的

setContentView()为什么叫setContentView ?

看到这里,或许有些朋友心中会有一个巨大的疑惑。不正确呀!平时在Activity中指定布局文件的时候,最外层的那个布局是能够指定大小的呀,layout_width和layout_height都是有作用的。

确实,这主要是由于。在setContentView()方法中,Android会自己主动在布局文件的最外层再嵌套一个FrameLayout。所以layout_width和layout_height属性才会有效果。那么我们来证实一下吧。改动MainActivity中的代码,例如以下所看到的:

MainActivity.java

public class MainActivity extends Activity {

    private LinearLayout mainLayout;

    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout = (LinearLayout) findViewById(R.id.main_layout);
ViewParent viewParent = mainLayout.getParent();
Log.d("TAG", "the parent of mainLayout is " + viewParent);
} }

打印结果:

LinearLayout的父布局确实是一个FrameLayout,而这个FrameLayout就是由系统自己主动帮我们加入上的。

讲到这里。尽管setContentView()方法大家都会用,但实际上Android界面显示的原理要比我们所看到的东西复杂得多。不论什么一个Activity中显示的界面事实上主要都由两部分组成,标题栏和内容布局。

标题栏就是在非常多界面顶部显示的那部分内容,比方刚刚我们的那个样例其中就有标题栏,能够在代码中控制让它是否显示。

而内容布局就是一个FrameLayout,这个布局的id叫作content,我们调用setContentView()方法时所传入的布局事实上就是放到这个FrameLayout中的。这也是为什么这种方法名叫作setContentView(),而不是叫setView()。

最后再附上一张Activity窗体的组成图吧,以便于大家更加直观地理解:

小结

本篇主要介绍了LayoutInflater的原理、使用方法,为深入理解View做了准备。

作者信息

View_01_LayoutInflater的原理、使用方法的更多相关文章

  1. fMRI数据分析处理原理及方法(转载)

    原文地址:http://www.cnblogs.com/minks/p/4889497.html 近年来,血氧水平依赖性磁共振脑功能成像(Blood oxygenation level-depende ...

  2. fMRI数据分析处理原理及方法

    来源: 整理文件的时候翻到的,来源已经找不到了囧感觉写得还是不错,贴在这里保存. 近年来,血氧水平依赖性磁共振脑功能成像(Blood oxygenation level-dependent funct ...

  3. Atitit.实现继承的原理and方法java javascript .net c# php ...

    Atitit.实现继承的原理and方法java javascript .net c# php ... 1. 实现继承的问题 1 2. 如何拷贝基类方法?采用prototype原型方式,通过冒充对象 1 ...

  4. Oracle中的SQL分页查询原理和方法详解

    Oracle中的SQL分页查询原理和方法详解 分析得不错! http://blog.csdn.net/anxpp/article/details/51534006

  5. 数据融合(data fusion)原理与方法

    数据融合(data fusion)原理与方法 数据融合(data fusion)最早被应用于军事领域.     现在数据融合的主要应用领域有:多源影像复合.机器人和智能仪器系统.战场和无人驾驶飞机.图 ...

  6. PHP 实现断点续传的原理和方法

    PHP 实现断点续传的原理和方法 0. http协议从1.1开始支持静态获取文件的部分内容,为多线程下载和断点续传提供了技术支持.它通过在Header里两个参数实现的,客户端发请求时对应的是Accep ...

  7. fMRI数据分析处理原理及方法————转自网络

    fMRI数据分析处理原理及方法 来源: 整理文件的时候翻到的,来源已经找不到了囧感觉写得还是不错,贴在这里保存. 近年来,血氧水平依赖性磁共振脑功能成像(Blood oxygenation level ...

  8. Smart3D系列教程1之《浅谈无人机倾斜摄影建模的原理与方法》

    一.引言 倾斜摄影测量技术是国际测绘遥感领域近年发展起来的一项高新技术,以大范围.高精度.高清晰的方式全面感知复杂场景,通过高效的数据采集设备及专业的数据处理流程生成的数据成果直观反映地物的外观.位置 ...

  9. 【APP自动化测试】Monkey的测试原理和方法

    参考资料:http://blog.csdn.net/io_field/article/details/52189972 一.Monkey测试原理:Monkey是Android中的一个命令行工具,可以运 ...

随机推荐

  1. 修改route.php文件对ThinkPHP快速注册路由

    THINKPHP快速注册路由方式可以用 return[ "test"=>"index/index/demo", 'getid/:id'=>'inde ...

  2. 【noip2016】蚯蚓(单调性+队列)

    题目贼长 大意是你有n个线段,每一秒你要拿出来最长的一个线段切成两段长度为[p*u](向下取整)和u-[p*u]两段(其中u是线段长,p是一个大于0小于1的实数)没被切的线段长度加q(0<q&l ...

  3. 前端之CSS选择器

    基本选择器 元素选择器 p {color: "red";} ID选择器 #i1 { background-color: red; } 类选择器 .c1 { font-size: 1 ...

  4. java 自己定义异常,记录日志简单说明!留着以后真接复制

    log4j 相关配制说明:http://blog.csdn.net/liangrui1988/article/details/17435139 自己定义异常 package org.rui.Excep ...

  5. [Poi] Setup PostCSS and Tailwind with Poi

    This lesson walks through setting up a Poi project using PostCSS and the popular Tailwind library fo ...

  6. 制作自己的特色PE----Mr.Zhang

    必备的文件和工具 win7.iso/win8.iso Windows系统ISO镜像 WimTool BOOT.WIM文件的改动 RegWorkShop 注冊表编辑和分析利器 UltraISO 改动wi ...

  7. iOS 一个ViewController上显示2个tableView的方法

    1.在StoryBoard上创建2个tableView,并用autolayout约束. 2.在ViewController上拖进来. @property (weak, nonatomic) IBOut ...

  8. vue20 父子组件数据交互

    子组件使用父组件数据 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&quo ...

  9. Windows 7: Update is not applicable to your computer

    https://www.sevenforums.com/windows-updates-activation/119088-update-not-applicable-your-computer.ht ...

  10. Word 操作组件介绍 - Spire.Doc

    http://www.cnblogs.com/liqingwen/p/5898368.html