组件和布局加载~LayoutInflater和findViewById() 的区别

本文深入探讨了Android应用开发中LayoutInflater和findViewById的区别与使用场景,详细介绍了如何通过这三个方法实例化和操作XML布局文件,以实现动态界面加载与组件获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、介绍
LayoutInflater作用类似于findViewById()。
具体作用:
1、LayoutInflater是在res/layout/下的xml布局文件,对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;
2、findViewById()是对于已经载入的界面,就可以使用Activity.findViewById()方法来获得其中的具体widget控件(如Button、TextView等)。

二、LayoutInflater 介绍-实例化

获得 LayoutInflater 实例的三种方式
1. LayoutInflater inflater = getLayoutInflater();//调用Activity的getLayoutInflater() 
2. LayoutInflater inflater = LayoutInflater.from(context);  
3. LayoutInflater inflater =  (LayoutInflater)context.getSystemService
                              (Context.LAYOUT_INFLATER_SERVICE);
其实,这三种方式本质是相同的,最后调用的都是:
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
即本质是都是调用的Context.getSystemService()。

三、inflate 方法
通过 sdk 的 api 文档,可以知道该方法有以下几种过载形式,返回值均是 View 对象,如下:
public View inflate (int resource, ViewGroup root) 
public View inflate (XmlPullParser parser, ViewGroup root)
public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)  
public View inflate (int resource, ViewGroup root, boolean attachToRoot)
参数解释:
resource:需要加载布局文件的id,意思是需要将这个布局文件中加载到Activity中来操作。
root:需要附加到resource资源文件的根控件,就是inflate()会返回一个View对象,如果第三个参数attachToRoot为true,就将这个root作为根对象返回,否则仅仅将这个root对象的LayoutParams属性附加到resource对象的根布局对象上,也就是布局文件resource的最外层的View上,比如是一个LinearLayout或者其它的Layout对象。如果提供root(不传null)时,返回值其实就是这个root,这个方法就是把xml解析成view之后挂载这个root下。如果传null(不提供root),返回值也是View,它就是xml布局里面的根节点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值