LayoutInflater 的基本使用; LayoutInflater ,setContentView,findViewById三者的对比。

来源:互联网 发布:网络综艺 收益 奇葩说 编辑:程序博客网 时间:2024/06/05 18:22

在代码中,我们时常会使用LayoutInflater来实例化 layout中的布局。兴趣使然就去查阅了一下相关的资料做一个自己的总结。


说到实例化 xml文件成View,我们第一个会想起的是 setContentView()方法 以及指定widget控件的findViewById()方法;下面总结一个这之中的相同点和区别。

1:三者基本作用对比:

1:setContentView

在setContentView()时会指定对应的View。一旦调用立刻显示出所对应的View。一般在Activity和Fragment的onCreate()方法中调用。

2:findViewById

findViewById():  寻找对应的View包含的widget如:Button,TextView:

3:LayoutInfalter   

LayoutInfalter:动态的在代码中实例化 layout中的View不会立即显示,有需要时,再拿来填充Dialog,listView的item等;


2:LayoutInflater 使用的两种方式:

1:从对应的context中获得:

LayoutInflater inflater = LayoutInflater.from(this);View view = inflater.inflater(R.layout.main, null); //第二个参数是ViewGroup.可以为null;


 2:通过SystemService获得

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


注:从源码看,两种方法做了同一件事情。

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

3:setContentView和LayoutInflater的区别;

虽然都是实例化Layout中的xml布局,不过setContentView只在activity中onCreat()使用;一旦调用界面会立即显示出来。

而LayoutInflater实例化view后不会立刻显示出来。可以在各种地方使用,需要的时候再给需要的控件显示和填充就可以了。


参考:

http://blog.sina.com.cn/s/blog_629b701e0100rg4d.html  该文章说明LayoutInflater的作用和使用方式。



0 0
原创粉丝点击