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的作用和使用方式。
- LayoutInflater 的基本使用; LayoutInflater ,setContentView,findViewById三者的对比。
- Android setContentView、LayoutInflater、findViewById
- setContentView() 、LayoutInflater的区别
- setContentView() 、LayoutInflater的区别
- LayoutInflater---LayoutInflater的使用
- setContentView与LayoutInflater的不同之处
- android setContentView() 、LayoutInflater的区别
- LayoutInflater与findViewById的用法
- LayoutInflater和findViewById的区别
- LayoutInflater和findViewById() 的区别
- LayoutInflater及findViewById使用
- android LayoutInflater、setContentView、findviewbyid 区分解析
- android开发中使用setContentView和LayoutInflater的点点滴滴
- setContentView()与LayoutInflater.from()的区别-android
- Android LayoutInflater 【 一个类似于findViewById的神器】
- Android LayoutInflater详解 与 findViewById() 的区别
- 【LayoutInflater】Android 中LayoutInflater的使用!
- LayoutInflater的使用,inflate
- ios开发swift中字符串生成二维码
- uva10791(数论)
- 练习6.17
- C获取linux系统环境变量方法(Environment Variables)
- MAC OS中配置opencv环境并用IntelliJ建立工程(JAVA)
- LayoutInflater 的基本使用; LayoutInflater ,setContentView,findViewById三者的对比。
- 三十分钟掌握STL
- OOM和Memory Leak
- 练习6.21
- ios开发swift中点击next调到下一个textfield中输入
- 《Cocos2d学习之路》一,前序和闹钟
- POJ1426 倍数01 BFS(同余模定理)
- 实习周记II
- ios开发swift中actionsheet的用法 从下面弹出