正确使用inflate,inflate原理解析,LayoutInflater

当在Android中使用LayoutInflater.inflate方法时,有时会出现视图显示不正确的状况,如宽高、内边距、外边距等设置失效。本文深入源码,探讨了正确的使用方法。关键点包括:1)当root不为空且attachToRoot为true时,返回的是root;2)root为空时,最外层布局参数无效;3)root为空,第三个参数失去意义;4)使用View.inflate(context, resource, root)时,root同时决定了attachToRoot的值。理解这些细节有助于避免潜在问题。" 108426007,8472163,Python字符串处理:查找、替换与分割,"['Python', '字符串处理', '编程语言']
摘要由CSDN通过智能技术生成

要看结论直接拉到底部


在用代码inflate一个XML布局文件添加到父容器时,偶尔会碰到这个inflate出来的view,会无法正确显示我们在xml中所定义的样子,比如可能会无法正确显示最外层定义的参数,width,height,padding,margin等等。今天研究了下inflate的源码,总算明白了正确使用的姿势。

inflate一个xml布局文件有多种方式:比如可以调用View类的inflate方法,

public static View inflate (Context context, int resource, ViewGroup root)

还可以调用LayoutInflater.from(context).inflate,但其实第一种方法最后也是调用LayoutInflater.from(context).inflate

public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }

所以我们只要分析public View inflate (int resource, ViewGroup root, boolean attachToRoot)这一个方法就行了

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

            final Context inflaterContext = mContext;
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context last
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值