LayoutInflater作用是将layout的xml布局文件实例化为View类对象。
区别:
setContentView()一旦调用, layout就会立刻显示UI;而inflate只会把Layout形成一个以view类实现成的对象,有需要时再用setContentView(view)显示出来。一般在activity中通过setContentView()将界面显示出来,但是如果在非activity中如何对控件布局设置操作了,这就需要LayoutInflater动态加载。
public View inflate(int Resourece,ViewGroup root)
作用:填充一个新的视图层次结构从指定的XML资源文件中
reSource:View的layout的ID
root: 生成的层次结构的根视图
return 填充的层次结构的根视图。如果参数root提供了,那么root就是根视图;否则填充的XML文件的根就是根视图。
其余几个重载的inflate函数类似。
获取LayoutInflater的方法有如下三种:
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.main, null ); LayoutInflater inflater = LayoutInflater.from(context); (该方法实质就是第一种方法,可参考源代码) View layout = inflater.inflate(R.layout.main, null ); LayoutInflater inflater = getLayoutInflater();(在Activity中可以使用,实际上是View子类下window的一个函数) View layout = inflater.inflate(R.layout.main, null ); |
一直有点纠结setContentView和inflate的区别找了一些资料。写了个小程序看了下:
public class MyInflate extends Activity{ private TextView tv; public void OnCreate(Bundle savedInstanceState){ super .onCreate(savedInstanceState); //setContentView(R.layout.main); //tv = (TextView) findViewById(R.id.tv); LayoutInflater inflate = LayoutInflater.from( this ); View view = inflate.inflate(R.layout.main, null ); setContentView(view); } } |
上述注释掉的代码和没有注释掉的代码两种情况是相同的。
相关推荐
android inflate demo,方便新手使用,下载导入android studio就可直接运行,简单明了的展现inflate不同参数的区别
Android LayoutInflater.inflate()详解 深入理解LayoutInflater.inflate() 由于我们很容易习惯公式化的预置代码,有时我们会忽略很优雅的细节。LayoutInflater以及它在Fragment的onCreateView()中填充View的方式...
帮助你更好的理解LayoutInflate中的inflate方法,以后想怎么用怎么用
LayoutInflater源码分析 inflate方法的区别
博客《ListView滑动删除实现之一——merge标签与LayoutInflater.inflate()》对应源码,博客地址:http://blog.csdn.net/harvic880925/article/details/45155965
主要介绍了Android LayoutInflater.inflate源码分析的相关资料,需要的朋友可以参考下
主要介绍了Android 中LayoutInflater.inflate()方法的介绍的相关资料,希望通过本文大家能掌握这部分内容,需要的朋友可以参考下
LayoutInflater.from(context).inflate()方法的调研
本文实例讲述了Android开发中LayoutInflater用法。分享给大家供大家参考,具体如下: 在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/...
本文主要介绍Android 中Inflate 方法的用法, 在开发Android应用过程中,可以在程序中应用 Inflate()方法加载新布局,希望能帮助有需要的朋友
Android LayoutInflater加载布局详解 对于有一定Android开发经验的同学来说,一定使用过LayoutInflater.inflater()来加载布局文件,但并不一定去深究过它的原理,比如 1.LayoutInflater为什么可以加载layout文件? ...
LayoutInflater详解 里面有详细的操作哦
NULL 博文链接:https://yufeng-zhu.iteye.com/blog/1676207
由于本人刚刚学习Android 对于getViewById和getLayoutInflater().inflate()的方法该如何使用不知如何分别,这里就上网查下资料整理下,大家可以看下。 LayoutInflater 要明白这个问题首先要知道什么是...