LayoutInflater—— 你可能对它并不了解甚至错误使用

2023-10-17 20:58

本文主要是介绍LayoutInflater—— 你可能对它并不了解甚至错误使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!



今天,看到了一篇文章讲LayoutInflater的用法,瞬间感觉自己对这个类确实不够了解,于是简单的看了下LayoutInflater类的源代码,对这个类有了新的认识。

首先,LayoutInflater这个类是用来干嘛的呢?

我们最常用的便是LayoutInflater的inflate方法,这个方法重载了四种调用方式,分别为:

1. public View inflate(int resource, ViewGroup root)

2. public View inflate(int resource, ViewGroup root, boolean attachToRoot)

3.public View inflate(XmlPullParser parser, ViewGroup root)

4.public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)

这四种使用方式中,我们最常用的是第一种方式,inflate方法的主要作用就是将xml转换成一个View对象,用于动态的创建布局。虽然重载了四个方法,但是这四种方法最终调用的,还是第四种方式。第四种方式也很好理解,内部实现原理就是利用Pull解析器,对Xml文件进行解析,然后返回View对象。

我们以我们经常使用的第一种形式为例,你在重写BaseAdapter的getView方法的时候是否这样做过

public View getView(int position, View convertView, ViewGroup parent) {if (convertView == null) {convertView = inflate(R.layout.item_row, null);}return convertView;
}
inflate方法有三个参数,分别是

1.resource布局的资源id

2.root填充的根视图

3.attachToRoot是否将载入的视图绑定到根视图中

在这个例子中,我们将root参数设为空,功能确实实现了,但是这里还隐藏着一个隐患,这种方式并不是inflate正确的使用姿势,下面我们通过一个Demo,来说一下这样使用造成的弊端。

首先,我们建立一个这样的项目


这里三个界面,一个主界面,两个测试界面,布局文件中,主界面只负责界面跳转,两个测试界面都是一个简单的Listview,item布局显示效果如下



对应的布局文件如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="60dp"android:background="@android:color/holo_orange_light"android:gravity="center"android:orientation="vertical" ><TextViewandroid:id="@+id/tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="11"android:textColor="@android:color/black"android:textSize="22sp" /></LinearLayout>

OneActivity的代码如下

public class OneActivity extends Activity {private ListView list1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_one);list1 = (ListView) findViewById(R.id.list1);list1.setAdapter(new MyAdapter(this));}private class MyAdapter extends BaseAdapter {private LayoutInflater inflater;MyAdapter(Context context) {inflater = LayoutInflater.from(context);}@Overridepublic int getCount() {return 20;}@Overridepublic Object getItem(int position) {return position;}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {if (convertView == null) {convertView = inflater.inflate(R.layout.item_list, null);}TextView tv = (TextView) convertView.findViewById(R.id.tv);tv.setText(position+"");return convertView;}}}

TwoActivity的代码如下

public class TwoActivity extends Activity {private ListView list2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_two);list2 = (ListView) findViewById(R.id.list2);list2.setAdapter(new MyAdapter(this));}private class MyAdapter extends BaseAdapter {private LayoutInflater inflater;MyAdapter(Context context) {inflater = LayoutInflater.from(context);}@Overridepublic int getCount() {return 20;}@Overridepublic Object getItem(int position) {return position;}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {if (convertView == null) {convertView = inflater.inflate(R.layout.item_list, parent,false);}TextView tv = (TextView) convertView.findViewById(R.id.tv);tv.setText(position + "");return convertView;}}}

两个文件最关键的区别就一句话,

在getView方法中,OneActivity是

convertView = inflater.inflate(R.layout.item_list, null);

在getView方法中,TwoActivity是

convertView = inflater.inflate(R.layout.item_list, parent,false);

我们先看一下显示效果,再说两者的区别

OneActivity效果



TwoActivity的显示效果



我们可以很明显的看出来,使用第一种方式,根布局的高度设置60dp没有起作用,系统还是按照包裹内容的方式加载的,为什么会产生这种效果呢?我们从需要inflate方法的源代码中找一下答案。

首先,方式一的源代码实现

public View inflate(XmlPullParser parser, ViewGroup root) {return inflate(parser, root, root != null);}

当我们使用方式一,并且第二个参数传入null的时候,默认调用的是下面的方法,并且attachToRoot是false

public View inflate(int resource, ViewGroup root, boolean attachToRoot) {if (DEBUG) System.out.println("INFLATING from resource: " + resource);XmlResourceParser parser = getContext().getResources().getLayout(resource);try {return inflate(parser, root, attachToRoot);} finally {parser.close();}}

在这一个方法中,pull解析器将资源id转化成XmlResourceParser对象,又传给了第四种方式,所以我们需要重点看的还是第四种方式是如何实现的

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {synchronized (mConstructorArgs) {Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");final AttributeSet attrs = Xml.asAttributeSet(parser);Context lastContext = (Context)mConstructorArgs[0];mConstructorArgs[0] = mContext;View result = root;try {// Look for the root node.int type;while ((type = parser.next()) != XmlPullParser.START_TAG &&type != XmlPullParser.END_DOCUMENT) {// Empty}if (type != XmlPullParser.START_TAG) {throw new InflateException(parser.getPositionDescription()+ ": No start tag found!");}final String name = parser.getName();if (DEBUG) {System.out.println("**************************");System.out.println("Creating root view: "+ name);System.out.println("**************************");}if (TAG_MERGE.equals(name)) {if (root == null || !attachToRoot) {throw new InflateException("<merge /> can be used only with a valid "+ "ViewGroup root and attachToRoot=true");}rInflate(parser, root, attrs, false);} else {// Temp is the root view that was found in the xmlView temp;if (TAG_1995.equals(name)) {temp = new BlinkLayout(mContext, attrs);} else {temp = createViewFromTag(root, name, attrs);}ViewGroup.LayoutParams params = null;if (root != null) {if (DEBUG) {System.out.println("Creating params from root: " +root);}// Create layout params that match root, if suppliedparams = 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);}}if (DEBUG) {System.out.println("-----> start inflating children");}// Inflate all children under temprInflate(parser, temp, attrs, true);if (DEBUG) {System.out.println("-----> done inflating children");}// We are supposed to attach all the views we found (int temp)// to root. Do that now.if (root != null && attachToRoot) {root.addView(temp, params);}// Decide whether to return the root that was passed in or the// top view found in xml.if (root == null || !attachToRoot) {result = temp;}}} catch (XmlPullParserException e) {InflateException ex = new InflateException(e.getMessage());ex.initCause(e);throw ex;} catch (IOException e) {InflateException ex = new InflateException(parser.getPositionDescription()+ ": " + e.getMessage());ex.initCause(e);throw ex;} finally {// Don't retain static reference on context.mConstructorArgs[0] = lastContext;mConstructorArgs[1] = null;}Trace.traceEnd(Trace.TRACE_TAG_VIEW);return result;}}

代码比较长,我们重点关注下面的代码

if (root != null) {if (DEBUG) {System.out.println("Creating params from root: " +root);}// Create layout params that match root, if suppliedparams = 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);}}

这些代码的意思就是,当我们传进来的root参数不是空的时候,并且attachToRoot是false的时候,也就是上面的TwoActivity的实现方式的时候,会给temp设置一个LayoutParams参数。那么这个temp又是干嘛的呢?

<pre name="code" class="java">// We are supposed to attach all the views we found (int temp)// to root. Do that now.if (root != null && attachToRoot) {root.addView(temp, params);}// Decide whether to return the root that was passed in or the// top view found in xml.if (root == null || !attachToRoot) {result = temp;}


 

现在应该明白了吧,当我们传进来的root不是null,并且第三个参数是false的时候,这个temp就被加入到了root中,并且把root当作最终的返回值返回了。而当我们设置root为空的时候,没有设置LayoutParams参数的temp对象,作为返回值返回了。

因此,我们可以得出下面的结论:

1.若我们采用convertView = inflater.inflate(R.layout.item_list, null);方式填充视图,item布局中的根视图的layout_XX属性会被忽略掉,然后设置成默认的包裹内容方式

2.如果我们想保证item的视图中的参数不被改变,我们需要使用convertView = inflater.inflate(R.layout.item_list, parent,false);这种方式进行视图的填充

3.除了使用这种方式,我们还可以设置item布局的根视图为包裹内容,然后设置内部控件的高度等属性,这样就不会修改显示方式了。


最后,给出那篇文章的链接http://blog.jobbole.com/72156/大家可以去看看

这篇关于LayoutInflater—— 你可能对它并不了解甚至错误使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/227914

相关文章

C语言中联合体union的使用

本文编辑整理自: http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=179471 一、前言 “联合体”(union)与“结构体”(struct)有一些相似之处。但两者有本质上的不同。在结构体中,各成员有各自的内存空间, 一个结构变量的总长度是各成员长度之和。而在“联合”中,各成员共享一段内存空间, 一个联合变量

Tolua使用笔记(上)

目录   1.准备工作 2.运行例子 01.HelloWorld:在C#中,创建和销毁Lua虚拟机 和 简单调用。 02.ScriptsFromFile:在C#中,对一个lua文件的执行调用 03.CallLuaFunction:在C#中,对lua函数的操作 04.AccessingLuaVariables:在C#中,对lua变量的操作 05.LuaCoroutine:在Lua中,

C++工程编译链接错误汇总VisualStudio

目录 一些小的知识点 make工具 可以使用windows下的事件查看器崩溃的地方 dumpbin工具查看dll是32位还是64位的 _MSC_VER .cc 和.cpp 【VC++目录中的包含目录】 vs 【C/C++常规中的附加包含目录】——头文件所在目录如何怎么添加,添加了以后搜索头文件就会到这些个路径下搜索了 include<> 和 include"" WinMain 和

Vim使用基础篇

本文内容大部分来自 vimtutor,自带的教程的总结。在终端输入vimtutor 即可进入教程。 先总结一下,然后再分别介绍正常模式,插入模式,和可视模式三种模式下的命令。 目录 看完以后的汇总 1.正常模式(Normal模式) 1.移动光标 2.删除 3.【:】输入符 4.撤销 5.替换 6.重复命令【. ; ,】 7.复制粘贴 8.缩进 2.插入模式 INSERT

Lipowerline5.0 雷达电力应用软件下载使用

1.配网数据处理分析 针对配网线路点云数据,优化了分类算法,支持杆塔、导线、交跨线、建筑物、地面点和其他线路的自动分类;一键生成危险点报告和交跨报告;还能生成点云数据采集航线和自主巡检航线。 获取软件安装包联系邮箱:2895356150@qq.com,资源源于网络,本介绍用于学习使用,如有侵权请您联系删除! 2.新增快速版,简洁易上手 支持快速版和专业版切换使用,快速版界面简洁,保留主

如何免费的去使用connectedpapers?

免费使用connectedpapers 1. 打开谷歌浏览器2. 按住ctrl+shift+N,进入无痕模式3. 不需要登录(也就是访客模式)4. 两次用完,关闭无痕模式(继续重复步骤 2 - 4) 1. 打开谷歌浏览器 2. 按住ctrl+shift+N,进入无痕模式 输入网址:https://www.connectedpapers.com/ 3. 不需要登录(也就是

Toolbar+DrawerLayout使用详情结合网络各大神

最近也想搞下toolbar+drawerlayout的使用。结合网络上各大神的杰作,我把大部分的内容效果都完成了遍。现在记录下各个功能效果的实现以及一些细节注意点。 这图弹出两个菜单内容都是仿QQ界面的选项。左边一个是drawerlayout的弹窗。右边是toolbar的popup弹窗。 开始实现步骤详情: 1.创建toolbar布局跟drawerlayout布局 <?xml vers

vue同页面多路由懒加载-及可能存在问题的解决方式

先上图,再解释 图一是多路由页面,图二是路由文件。从图一可以看出每个router-view对应的name都不一样。从图二可以看出层路由对应的组件加载方式要跟图一中的name相对应,并且图二的路由层在跟图一对应的页面中要加上components层,多一个s结尾,里面的的方法名就是图一路由的name值,里面还可以照样用懒加载的方式。 页面上其他的路由在路由文件中也跟图二是一样的写法。 附送可能存在

C#中,decimal类型使用

在Microsoft SQL Server中numeric类型,在C#中使用的时候,需要用decimal类型与其对应,不能使用int等类型。 SQL:numeric C#:decimal

探索Elastic Search:强大的开源搜索引擎,详解及使用

🎬 鸽芷咕:个人主页  🔥 个人专栏: 《C++干货基地》《粉丝福利》 ⛺️生活的理想,就是为了理想的生活! 引入 全文搜索属于最常见的需求,开源的 Elasticsearch (以下简称 Elastic)是目前全文搜索引擎的首选,相信大家多多少少的都听说过它。它可以快速地储存、搜索和分析海量数据。就连维基百科、Stack Overflow、