获取LayoutInflater有三种不同的方式,那么这三种方式有什么区别呢?
源码:
① LayoutInflater inflater = LayoutInflater.from(context); (LayoutInflater类)
<span style="font-size:14px;">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;
}</span>
② LayoutInflater inflater = getLayoutInflater();(Activity类)
<span style="font-size:14px;color:#330033;">public LayoutInflater getLayoutInflater() {
return getWindow().getLayoutInflater();
}</span>
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
③ LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); (Activity类)
<span style="font-size:14px;color:#330033;"> public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater";</span>
ps: Use with getSystemService(java.lang.String) to retrieve a android.view.LayoutInflater for inflating layout resources in this context.
从源码上,三种方式在本质都是一样的,②是调用①的方法,而①则是在调用③。java很有意思就是这样子调来调去,给人一种似是而非的感觉。
对于getSystemService类,我们在源码中可以看到提供了很多的Service:
WINDOW_SERVICE
(WindowManager) 管理打开的窗口程序
LAYOUT_INFLATER_SERVICE (LayoutInflater) 取得xml里定义的view
ACTIVITY_SERVICE
(ActivityManager
) 管理应用程序的系统状态
POWER_SERVICE
(PowerManger
) 电源的服务
ALARM_SERVICE
(AlarmManager
) 闹钟的服务
NOTIFICATION_SERVICE
(NotificationManager
)状态栏的服务
KEYGUARD_SERVICE
(KeyguardManager
) 键盘锁的服务
LOCATION_SERVICE
(LocationManager
) 位置的服务
SEARCH_SERVICE
(SearchManager
) 搜索的服务
VEBRATOR_SERVICE
(Vebrator
) 手机震动的服务
CONNECTIVITY_SERVICE
(Connectivity
) 网络连接的服务
WIFI_SERVICE
(WifiManager
) WiFi服务
TELEPHONY_SERVICE
(TeleponyManager
) 电话服务
未完待续
本文详细介绍了在Android开发中获取LayoutInflater的三种常见方式,并通过源码分析揭示了它们之间的内在联系及区别。此外,还列举了Context中提供的多种Service及其用途。
8481

被折叠的 条评论
为什么被折叠?



