Android LayoutInflater 详解

Android LayoutInflater 详解

简介:
在实际开发中 LayoutInflater这个类还是非常有用的,它的作用类似于 findViewById()
不同点是 LayoutInflater是用来找 res/layout/下的 xml布局文件,并且实例化;而 findViewById()是找 xml布局文件下的具体 widget控件(如Button,TextView等等)。
使用场景:
①对于一个没有被载入或者想要动态载入的界面,都需要使用 LayoutInflater.inflater()来载入。
②对于一个已经载入的界面,可以使用 Activity.findViewById()方法来获取其中的界面元素。
获取LayoutInflater实例的三种方式:
// 方式1
// 调用Activity的getLayoutInflater()
LayoutInflater inflater = getLayoutInflater();
// 方式2
LayoutInflater inflater = LayoutInflater.from(context);
// 方式3
LayoutInflater inflater = LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
其实,这三种方式本质上是一样的,从源码中可以看出:

ActivitygetLayoutInflater()方法调用的是PhoneWindowgetLayoutInflater()方法,该方法源码为:

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里定义的view
ACTIVITY_SERVICEActivityManager管理应用程序的系统状态
POWER_SERVICEPowerManger电源的服务
ALARM_SERVICEAlarmManager闹钟的服务
NOTIFICATION_SERVICENotificationManager状态栏的服务
KEYGUARD_SERVICEKeyguardManager键盘锁的服务
LOCATION_SERVICELocationManager位置的服务,如GPS
SEARCH_SERVICESearchManager搜索的服务
VEBRATOR_SERVICEVebrator手机震动的服务
CONNECTIVITY_SERVICEConnectivity网络连接的服务
WIFI_SERVICEWifiManagerWi-Fi服务
TELEPHONY_SERVICETeleponyManager电话服务

示例代码如下:

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 等)。
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值