您的位置:首页 > 移动开发 > Android开发

Android中LayoutInflater的使用

2013-06-17 15:44 459 查看
在实际工作中,事先写好的布局文件往往不能满足我们的需求,有时会根据情况在代码中自定义控件,这就需要用到LayoutInflater。
LayoutInflater在Android中是“扩展”的意思,作用类似于findViewById(),不同的是LayoutInflater是用来获得布局文件对象的,而

findViewById()是用来获得具体控件的。LayoutInflater经常在BaseAdapter的getView方法中用到,用来获取整个View并返回。

实现LayoutInflater的实例化共有3种方法,

(1).通过SystemService获得

LayoutInflaterinflater = (LayoutInflater)context.getSystemServices(Context.LAYOUT_INFLATER_SERVICES);

Viewview = inflater.inflate(R.layout.main, null);

(2).从给定的context中获得

LayoutInflaterinflater = LayoutInflater.from(context);

Viewview = inflater.inflate(R.layout.mian, null);

(3).LayoutInflaterinflater =getLayoutInflater();(在Activity中可以使用,实际上是View子类下window的一个函数)

Viewlayout = inflater.inflate(R.layout.main, null);

从源码中可以看出,这三种方法本质是一样的。

源代码:

publicPhoneWindow(Contextcontext) {

super(context);

mLayoutInflater= LayoutInflater.from(context);

}

可以看出它其实是调用LayoutInflater.from(context)。

LayoutInflater.from(context):

public static LayoutInflaterfrom(Context context) {

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

if(LayoutInflater== null){

thrownew AssertionError("LayoutInflaternot found.");

}

returnLayoutInflater;

}

可以看出它其实调用context.getSystemService()。

public View inflate(int Resource,ViewGroup root)

作用:从指定的XML资源文件中拓展一个新的视图层次结构

Resource:要加载的XML资源文件的ID

root: 生成的层次结构的根视图(可选)

return 拓展的层次结构的根视图。如果提供了root,那么root就是根视图;否则根视图是拓展的XML文件的根视图。

另外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 电话服务
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: