标签:
我们一般使用 LayoutInflater 做一件事:View inflate(int resource, ViewGroup root);
inflate() 的作用类似于 findViewById(); 不同的是 findViewById 用于查找某一具体 XML 下的具体的 widget 控件(如 TextView,Button 等待)而 inflate 则用于查找 /res/layout/文件夹下的 XML 布局文件并实例化,与 setContentView() 也有不同。
LayoutInflater inflater = LayoutInflater.from(this); View view=inflater.inflate(R.layout.ID, null);
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = getLayoutInflater();
虽然 Layout 也是 View 的子类,但在 Android 中如果想将 XML 中的 Layout 转换为 View 放入 .java 代码中操作,只能通过 Inflater,而不能通过 findViewById()。
两者的区别在于 setContentView 一旦调用,则立即显示 UI,而inflate只会把Layout形成一个以view类实现成的对象,有需要时再用setContentView(view)显示出来。一般在activity 中通过 setContentView 将界面显示出来,但是如果在非 activity 对控件布局设置操作,这需 LayoutInflater 动态加载。
标签:
原文地址:http://www.cnblogs.com/tannerBG/p/4341929.html