标签:findviewbyid 布局文件 android 控件 开发
LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;而findViewById()是找xml布局文件下的具体widget控件(如Button,TextView等等)。LayoutInflater.inflater()来载入。Activity.findViewById()方法来获取其中的界面元素。LayoutInflater实例的三种方式: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_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 | 位置的服务,如GPS |
| SEARCH_SERVICE | SearchManager | 搜索的服务 |
| VEBRATOR_SERVICE | Vebrator | 手机震动的服务 |
| CONNECTIVITY_SERVICE | Connectivity | 网络连接的服务 |
| WIFI_SERVICE | WifiManager | Wi-Fi服务 |
| TELEPHONY_SERVICE | TeleponyManager | 电话服务 |
示例代码如下:
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom, (ViewGroup)findViewById(R.id.test));
EditText editText = (EditText)view.findViewById(R.id.content);
// 注意:
// ·inflate 方法与 findViewById 方法不同;
// ·inflater 是用来找 res/layout 下的 xml 布局文件,并且实例化;
// ·findViewById() 是找具体 xml 布局文件中的具体 widget 控件(如:Button、TextView 等)。标签:findviewbyid 布局文件 android 控件 开发
原文地址:http://blog.csdn.net/biezhihua/article/details/43996289