Android LayoutInflater 详解
来源:互联网 发布:易语言七夕表白源码 编辑:程序博客网 时间:2024/05/29 16:47
简介:
在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;
而findViewById()是找xml布局文件下的具体widget控件(如Button,TextView等等)。
使用场景:
①对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflater()来载入。
②对于一个已经载入的界面,可以使用Activity.findViewById()方法来获取其中的界面元素。
获取LayoutInflater实例的三种方式:
// 方式1// 调用Activity的getLayoutInflater()LayoutInflater inflater = getLayoutInflater();// 方式2LayoutInflater inflater = LayoutInflater.from(context);// 方式3LayoutInflater inflater = LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
其实,这三种方式本质上是一样的,从源码中可以看出:Activity的getLayoutInflater()方法调用的是PhoneWindow的getLayoutInflater()方法,该方法源码为:
public PhoneWindow(Context context){ super(context); mLayoutInflater = LayoutInflater.from(context);}
可以看出其实调用的是LayoutInflater.from(context),而对于LayoutInflater.from(context)而言,它实际调用的是context.getSystemService(),请看如下源码:
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;}
结论:这三种方法的本质都是调用Context.getSystemService()这个方法。
getSystemService()是Android中非常重要的一个API,它是Activity的一个方法,根据传入的name得到对应的Object,然后转换成相应的服务对象。下面介绍一下系统相应的服务。
传入的Name返回的对象说明WINDOW_SERVICEWindowManager管理打开的窗口程序LAYOUT_INFLATER_SERVICELayoutInflater取得xml里定义的viewACTIVITY_SERVICEActivityManager管理应用程序的系统状态POWER_SERVICEPowerManger电源的服务ALARM_SERVICEAlarmManager闹钟的服务NOTIFICATION_SERVICENotificationManager状态栏的服务KEYGUARD_SERVICEKeyguardManager键盘锁的服务LOCATION_SERVICELocationManager位置的服务,如GPSSEARCH_SERVICESearchManager搜索的服务VEBRATOR_SERVICEVebrator手机震动的服务CONNECTIVITY_SERVICEConnectivity网络连接的服务WIFI_SERVICEWifiManagerWi-Fi服务TELEPHONY_SERVICETeleponyManager电话服务
0 0
- Android LayoutInflater详解
- Android LayoutInflater详解
- Android LayoutInflater详解
- Android LayoutInflater详解
- Android LayoutInflater详解
- Android 的LayoutInflater详解
- Android LayoutInflater详解
- Android LayoutInflater详解
- Android LayoutInflater详解
- Android LayoutInflater详解
- Android LayoutInflater详解
- Android LayoutInflater详解
- Android LayoutInflater详解
- Android LayoutInflater详解
- android系列: LayoutInflater详解
- Android LayoutInflater详解
- Android--LayoutInflater详解
- Android LayoutInflater详解
- poj 2503 Babelfish Trie
- java语言之单例设计模式
- uva 165 Stamps (回溯)
- hdu1016 Prime Ring Problem(DFS)
- 数组、结构体、指针1
- Android LayoutInflater 详解
- Ordering Tasks
- Linux内核分析MOOC课程汇编分析
- 有getter setter的属性在Inspector视图中设置值
- session与cookie的区别和联系?
- 数组、结构体、指针2
- 数学之美番外篇:进化论中的概率论
- hdu 3962 Microgene (ac自动机+矩阵优化(好题))
- ant 编译 aidl 报告错误: couldn't find import for class