关于findViewById()与Inflate()和setContentView()的关系我理了理,清晰多了,觉得很有必要记一记。
1.findViewById()与Inflate()的关系
findViewById()其实好理解,从layout上把控件找出来并转为一个对应的对象。
至于Inflate()则是把layout从xml文件中实例化成一个对象。这样findViewById才能在上面找出控件。
2. Inflate()与setContentView()的关系
如果仅从上面这样看Inflate()的功能,setContentView()效果也是一样的。实际也上也是把xml文件上的layout实例化显示.
如: setContentView(R.layout.main);
不过setContentView()一运行,界面马上就显示。Inflate()则只生成和操作对象,但是隐藏状态,不显示在界面上。显示还是要靠setContentView()。
3. 那Inflate()有什么价值呢?
Inflate()主要用在当前Activity中,控制别的layout,Fragment就经常用。
弹出窗口这类也是,通过Inflate()实现化出弹出窗口,然后再用findViewById()控制上面控件.
其实这个和CS界面开发时的搞法差不多。
4.附注:
另外附上从http://www.2cto.com/kf/201205/131136.html找来的说明,
这篇文章还进源码查看了一翻。发现其实本质都是调用context.getSystemServices(Context.LAYOUT_INFLATER_SERVICES)方法得到的。
实现LayoutInflater的实例化共有3种方法:
(1).通过SystemService获得
LayoutInflaterinflater = (LayoutInflater)context.getSystemServices(Context.LAYOUT_INFLATER_SERVICES);
Viewview = inflater.inflate(R.layout.main, null);
(2).从给定的context中获得
LayoutInflaterinflater = LayoutInflater.from(context);
Viewview = inflater.inflate(R.layout.mian, null);
(3).
LayoutInflaterinflater =getLayoutInflater();(在Activity中可以使用,实际上是View子类下window的一个函数)
Viewlayout = inflater.inflate(R.layout.main, null);
Android关于这部份的源码: