学习自定义View一段时间了,从开始的一窍不通到现在终于能写出点东西了,前面也写过几篇关于自定义view的博客,但是感觉这东西吧,一天不敲又忘记了,所以准备写一篇自定义View系列的博客,这也算是我这段时间学习自定义View总结的开篇,接下来还会有一系列的文章,支持我的朋友可以悄悄的点个赞,一起fighting!!!
既然是总结性的东西我们就要研究透一点,我们从源码看,不啰嗦了,开车了……

首先获取LayoutInflater的方式有两种:
方式一:

LayoutInflater inflater = LayoutInflater.from(context);
  • 1

方式二:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  • 1

其实方式一的from方法里面就是通过方式二的方式实现的

** Obtains the LayoutInflater from the given context.*/public static LayoutInflater from(Context context) {LayoutInflater LayoutInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);if (LayoutInflater == null) {throw new AssertionError("LayoutInflater not found.");}return LayoutInflater;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

好了,讲了怎么获取LayoutInflater实例了,我们该研究下inflater方法了,

 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();}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

可以看了inflater中需要传递三个参数,

Tables Are
resource 需要inflater的layout文件
root root布局
attachToroot 是否加到root布局中

先大致走一遍源码,

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {synchronized (mConstructorArgs) {Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");final AttributeSet attrs = Xml.asAttributeSet(parser);Context lastContext = (Context)mConstructorArgs[0];mConstructorArgs[0] = mContext;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, attrs, false, false);} else {// Temp is the root view that was found in the xmlfinal View temp = createViewFromTag(root, name, attrs, false);ViewGroup.LayoutParams params = null;if (root != null) {if (DEBUG) {System.out.println("Creating params from root: " +root);}// Create layout params that match root, if suppliedparams = 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 temprInflate(parser, temp, attrs, true, 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 (IOException 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;}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101

inflater中代码还不是很多,我们简单看看最主要的部分,我们可以看到这么一行代码

final View temp = createViewFromTag(root, name, inflaterContext, attrs);
  • 1

当XmlPullParser解析一边读一边解析到标签的时候,就去根据名字通过反射创建一个View。
当root!=null的时候,会Create layout params that match root, if supplied(创建一个属于root的params)

params = root.generateLayoutParams(attrs);
  • 1

当root=null的时候,此时的layoutParams为空,不理解也没关系,我待会会用例子讲解的。

当attachToroot=false的时候(不加入到root中)

 if (!attachToRoot) {temp.setLayoutParams(params);}
  • 1
  • 2
  • 3

当attachToroot=true的时候(加入到root中)

if (root != null && attachToRoot) {root.addView(temp, params);}
  • 1
  • 2
  • 3
  • 4

最后返回result,inflater的源码我们就大致过了一遍,接下来我会用例子一一讲解每一个用法,并且展示我们常见的一些错误。

首先我们准备一个叫botton的布局,里面就一个Button。

<?xml version="1.0" encoding="utf-8"?><Button          xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width=wrap_contentandroid:layout_height=wrap_contentandroid:text=Button></Button>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

主布局main.layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width=match_parentandroid:layout_height=match_parentandroid:id=@+id/id_content>
</RelativeLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

然后我们通过inflater加载出button然后添加到主布局id为id_content的RelativeLayout布局中,想必这对大家来说都是小菜一碟了。

public class MainActivity extends FragmentActivity {private RelativeLayout rl_content;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main2);rl_content= (RelativeLayout) findViewById(R.id.id_content);LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);//测试一id,null,falseView view= inflater.inflate(R.layout.bottom,null,false);rl_content.addView(view);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

运行效果:

好了,接着我们改改button的大小,宽度改为300dp

<?xml version="1.0" encoding="utf-8"?><Button          xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width=300dpandroid:layout_height=wrap_contentandroid:text=Button></Button>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

我们再看看效果:

没有变化咯,这是为什么呢?
我们把代码改改,传一个rl_content当做root

inflater.inflate(R.layout.bottom,rl_content,false);rl_content.addView(view);
  • 1
  • 2
  • 3

这时inflater会执行
params = root.generateLayoutParams(attrs);

if (root != null) {if (DEBUG) {System.out.println("Creating params from root: " +root);}// Create layout params that match root, if suppliedparams = 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);}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

我们运行代码:

按钮终于变大了,我们可以看到,如果我们不指定button的父控件的话
android:layout_width=300dp就会失效,因为只要有layout_标签的
属性的话,必须要有父控件,不然就没有意义了。
所以如果需要android:layout_width=300dp有效的话,还可以通过在xml布局中给Button一个父布局就ok了。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="100dp"android:layout_height="500dp"android:orientation="vertical"android:background="#00ff00"><Button
        xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width=300dpandroid:layout_height=wrap_contentandroid:text="Button"></Button>
</LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

这样既可~!!!!!

接下来说说以前遇到的坑了,
我们改改代码,把attachToroot改为true

 LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);View view= inflater.inflate(R.layout.bottom,rl_content,true);rl_content.addView(view);
  • 1
  • 2
  • 3

我们继续运行下代码:
程序直接报错了,报错信息为:
* Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first.*
大致就是说此View已经有一个父控件了,不能调用addView了。
我们看看源码当attachToroot改为true时 inflater中的代码,我们看到这么一段代码:

if (root != null && attachToRoot) {root.addView(temp, params);}
  • 1
  • 2
  • 3

看到这里我们恍然大悟了,也就是说在inflater方法中已经把view加入root中了,所以再加的话会报错。

当加载的布局为merge 类型的时候,必须加root,然后attachToRoot必须为true,不然会报错:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"><Button
        android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Button"/></merge>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

如果root为空或者attachToRoot为false时,运行效果:
直接报错了~!!
报错信息大致为:

throw new InflateException("<merge /> can be used only with a valid "+ "ViewGroup root and attachToRoot=true");
  • 1
  • 2

好了,讲到这里想必大家都应该对inflater方法有一个深刻的了解了,
没事多ctrl+左键吧,会有很多收获哦~!!!!3q

LayoutInflater.inflate()详解相关推荐

  1. Android LayoutInflater.inflate详解

    1. 作用 官方释义 Inflate a new view hierarchy from the specified xml resource 大概意思就是从给定的xml中加载view树. 2. 用法 ...

  2. LayoutInflater类详解

    http://www.cnblogs.com/top5/archive/2012/05/04/2482328.html 在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于 f ...

  3. LayoutInflater.from(this)、inflate 详解

    三种方式可以生成LayoutInflater  LayoutInflater inflater = LayoutInflater.from(this); LayoutInflater inflater ...

  4. LayoutInflater的inflate函数用法详解

    LayoutInflater的inflate函数用法详解 LayoutInflater作用是将layout的xml布局文件实例化为View类对象. 获取LayoutInflater的方法有如下三种: ...

  5. Android LayoutInflater详解

    Android LayoutInflater详解 在实际开发中LayoutInflater这个类还是非常有用的,它的作用类 似于findViewById().不同点是LayoutInflater是用来 ...

  6. Android LayoutInflater详解(转)

    在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById().不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例 ...

  7. 安卓 LayoutInflater详解

    导读 在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById(). 不同点是: LayoutInflater是用来找res/layout/下的xml布局文 ...

  8. android service layoutinflater,[转]Android LayoutInflater详解

    在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById().不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例 ...

  9. layoutinflater详解

    layoutinflater ListView的Adapter的getView方法中基本都会出现,使用inflate方法去加载一个布局,用于ListView的每个Item的布局,但是这三个方法究竟有什 ...

最新文章

  1. 《Unity开发实战》——2.2节创建画中画效果
  2. matlab学习——1.基本操作
  3. Docker镜像与容器命令
  4. springboot中下面哪一个作为jpa默认实现_35个超高频SpringBoot知识点(附解析),别怪我没给你机会收藏...
  5. HDU - 1547 Bubble Shooter(dfs+连通块+模拟)
  6. 纪中A组模拟赛总结(2021.7.17)
  7. 形态学运算中腐蚀,膨胀,开运算和闭运算
  8. 如何使用SQL Server配置管理器
  9. 什么是git subcommand,如何创建git子命令?
  10. 几个不错的网站(转)
  11. BLUE引擎或者LEG引擎M2架设时提示【该授权文件已过期】原因和解决方法
  12. ATM维护人员教大家正确使用银行卡和取款机
  13. android 监听多个广播,同一个广播接收器监听多个广播及多个广播接收器监听同一个广播...
  14. python安装以后怎么打开_安装python后如何打开
  15. Java回炉学习(三)
  16. 国内外技术论坛的区别
  17. mysql 多表 left join_MySql left join 多表连接查询优化语句
  18. 数学史资料:古巴比伦数学
  19. 攻城狮应该明白的浏览器工作原理~
  20. 360buy二次融资

热门文章

  1. 【Android C#开发】Xamarin环境搭建
  2. D-link850路由器漏洞挖掘与利用
  3. niubia z5s mini 大游戏找不到数据包解决办法,2次补充,超详细步骤!
  4. 如何在vue项目中设置首页
  5. 【二分查找】有这一篇足够了
  6. 虹科PXI解决方案助力新能源汽车电池管理系统(BMS)测试
  7. beyond compare3 序列号
  8. 2.机器学习基础(五)
  9. 可视化编程——如何自定义鼠标光标
  10. Django ORM的外键ForeignKey中的on_delete的参数解析