博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用LayoutInflater的inflate方法的注意事项
阅读量:4029 次
发布时间:2019-05-24

本文共 1655 字,大约阅读时间需要 5 分钟。

获取LayoutInflater实例的常规方法

//方法1LayoutInflater layoutInflater = LayoutInflater.from(context);  //方法2LayoutInflater layoutInflater = (LayoutInflater) context          .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

注意inflate方法的第二,第三个参数的使用

这里写图片描述

如上图所示:如果rootView不为空且attachToRoot为true,即传入rootVeiw且希望布局文件挂到RootView上,inflate方法返回的是rootView,否则返回inflate的View(布局文件中最外层的view,称之为布局文件的根view)

如下是关键的源码(View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)中的代码)

//一开始 View result = root; ..... // Temp is the root view that was found in the xml final View temp = createViewFromTag(root, name, inflaterContext, attrs); // Decide whether to return the root that was passed in or the // top view found in xml. if (root == null || !attachToRoot) {     result = temp; }

最常遇到的问题-布局文件的根View排版参数丢失了

如第二点提到的,如果第二个参数没有赋值,布局文件的排版版参数(LayoutParams)是不生效的(会丢失),关键代码如下图所示

// Temp is the root view that was found in the xmlfinal View temp = createViewFromTag(root, name, inflaterContext, attrs);ViewGroup.LayoutParams params = null;if (root != null) {    // Create layout params that match root, if supplied    params = root.generateLayoutParams(attrs);    if (!attachToRoot) {        // Set the layout params for temp if we are not        // attaching. (If we are, we use addView, below)        //设备布局文件的根节点的排版参数        temp.setLayoutParams(params);     }}// Inflate all children under temp against its context.rInflateChildren(parser, temp, attrs, true);                  // We are supposed to attach all the views we found (int temp)// to root. Do that now.if (root != null && attachToRoot) {    //addView的内部也会设置布局文件的根view的排版参数    root.addView(temp, params);}
你可能感兴趣的文章
在android上运行native可执行程序
查看>>
Phone双模修改涉及文件列表
查看>>
android UI小知识点
查看>>
Android之TelephonyManager类的方法详解
查看>>
android raw读取超过1M文件的方法
查看>>
ubuntu下SVN服务器安装配置
查看>>
MPMoviePlayerViewController和MPMoviePlayerController的使用
查看>>
CocoaPods实践之制作篇
查看>>
[Mac]Mac 操作系统 常见技巧
查看>>
苹果Swift编程语言入门教程【中文版】
查看>>
捕鱼忍者(ninja fishing)之游戏指南+游戏攻略+游戏体验
查看>>
iphone开发基础之objective-c学习
查看>>
iphone开发之SDK研究(待续)
查看>>
计算机网络复习要点
查看>>
Variable property attributes or Modifiers in iOS
查看>>
NSNotificationCenter 用法总结
查看>>
C primer plus 基础总结(一)
查看>>
剑指offer算法题分析与整理(一)
查看>>
剑指offer算法题分析与整理(三)
查看>>
部分笔试算法题整理
查看>>