[Android] 转-LayoutInflater丢失View的LayoutParams
原文地址:http://lmbj.net/blog/layoutinflater-and-layoutparams/
View view = inflater.inflate(R.layout.item, null);
在使用类似以上方法获取view时会遇到的一个问题就是布局文件中定义的LayoutParams被忽略了。以下三个stackoverflow问题就是这样:
http://stackoverflow.com/questions/5288435/layout-params-of-loaded-view-are-ignored
http://stackoverflow.com/questions/5026926/making-sense-of-layoutinflater
http://stackoverflow.com/questions/2738670/layoutinflater-ignoring-parameters
都说这样使用就可以了:
View view = inflater.inflate( R.layout.item /* resource id */, parent /* parent */,false /*attachToRoot*/);
至此问题已经解决了,但是三个问题都没有提到为什么要这样调用才行。
感兴趣的我们到源码里来找答案,LayoutInflater的inflate方法,最后都是调用的同一个方法:
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
原因自然在这个方法里,大概意思就是只有ViewGroup root不为空才会读取View的LayoutParams。attachToRoot = true
的时候,会把View添加到root中。而大多情况不希望被addView到root中,自然要赋值为flase,这样就是上面的解决方案了。
可以参看LayoutInflater的inflate方法相关的源码:
/**
* Inflate a new view hierarchy from the specified xml resource. Throws
* {@link InflateException} if there is an error.
*
* @param resource ID for an XML layout resource to load (e.g.,
* <code>R.layout.main_page</code>)
* @param root Optional view to be the parent of the generated hierarchy.
* @return The root View of the inflated hierarchy. If root was supplied,
* this is the root View; otherwise it is the root of the inflated
* XML file.
*/
public View inflate(int resource, ViewGroup root) {
return inflate(resource, root, root != null);
}
/**
* Inflate a new view hierarchy from the specified xml node. Throws
* {@link InflateException} if there is an error. *
* <p>
* <em><strong>Important</strong></em> For performance
* reasons, view inflation relies heavily on pre-processing of XML files
* that is done at build time. Therefore, it is not currently possible to
* use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
*
* @param parser XML dom node containing the description of the view
* hierarchy.
* @param root Optional view to be the parent of the generated hierarchy.
* @return The root View of the inflated hierarchy. If root was supplied,
* this is the root View; otherwise it is the root of the inflated
* XML file.
*/
public View inflate(XmlPullParser parser, ViewGroup root) {
return inflate(parser, root, root != null);
}
/**
* Inflate a new view hierarchy from the specified xml resource. Throws
* {@link InflateException} if there is an error.
*
* @param resource ID for an XML layout resource to load (e.g.,
* <code>R.layout.main_page</code>)
* @param root Optional view to be the parent of the generated hierarchy (if
* <em>attachToRoot</em> is true), or else simply an object that
* provides a set of LayoutParams values for root of the returned
* hierarchy (if <em>attachToRoot</em> is false.)
* @param attachToRoot Whether the inflated hierarchy should be attached to
* the root parameter? If false, root is only used to create the
* correct subclass of LayoutParams for the root view in the XML.
* @return The root View of the inflated hierarchy. If root was supplied and
* attachToRoot is true, this is root; otherwise it is the root of
* the inflated XML file.
*/
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();
}
}
/**
* Inflate a new view hierarchy from the specified XML node. Throws
* {@link InflateException} if there is an error.
* <p>
* <em><strong>Important</strong></em> For performance
* reasons, view inflation relies heavily on pre-processing of XML files
* that is done at build time. Therefore, it is not currently possible to
* use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
*
* @param parser XML dom node containing the description of the view
* hierarchy.
* @param root Optional view to be the parent of the generated hierarchy (if
* <em>attachToRoot</em> is true), or else simply an object that
* provides a set of LayoutParams values for root of the returned
* hierarchy (if <em>attachToRoot</em> is false.)
* @param attachToRoot Whether the inflated hierarchy should be attached to
* the root parameter? If false, root is only used to create the
* correct subclass of LayoutParams for the root view in the XML.
* @return The root View of the inflated hierarchy. If root was supplied and
* attachToRoot is true, this is root; otherwise it is the root of
* the inflated XML file.
*/
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
final AttributeSet attrs = Xml.asAttributeSet(parser);
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);
} else {
// Temp is the root view that was found in the xml
View temp = createViewFromTag(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 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);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp
rInflate(parser, temp, attrs);
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;
}
return result;
}
}
[Android] 转-LayoutInflater丢失View的LayoutParams的更多相关文章
- java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.L(转)
09-09 10:19:59.979: E/AndroidRuntime(2767): FATAL EXCEPTION: main09-09 10:19:59.979: E/AndroidRuntim ...
- Android什么时候进行View中Background的加载
对大多数Android的开发者来说,最经常的操作莫过于对界面进行布局,View中背景图片的加载是最经常做的.但是我们很少关注这个过程,这篇文章主要解析view中背景图片加载的流程.了解view中背景图 ...
- android 中的 window,view,activity具体关系
通过讨论这个问题,我们能够见识到google是对面向对象模式的理解,能够理解android底层的一些调用.这也是一道很常见的面试题. 我们这篇文章就来解决这四个问题: Android 中view的显 ...
- Android应用程序窗体View的创建过程
View类是android中非常重要的一个类.view是应用程序界面的直观体现,我们看到的应用程序界面就能够看作是View(视图)组成的. 那么我们应用程序的界面是怎么创建的呢,也就是应用程序的Vie ...
- android中LayoutInflater详解与使用
android的LayoutInflater用来得到一个布局文件,也就是xxx.xml,而我们常用的findviewbyid是用来取得布局文件里的控件或都布局.inflater即为填充的意思,也就是说 ...
- Android 的窗口管理系统 (View, Canvas, WindowManager)
http://blog.csdn.net/ritterliu/article/details/39295271 From漫天尘沙 在图解Android - Zygote 和 System Server ...
- Android学习笔记之View
转载: 0.7562018.10.22 21:44:10字数 5,423阅读 189 导图 一.View事件体系 1.什么是 View 和 View的位置坐标 View是什么: View 是一种界 ...
- Android的视图(View)组件
Android的绝大部分UI组件都放在android.widget包及其子包.android,view包及其子包中,Android应用的所有UI组件都继承了View类,View组件非常类似于Swing ...
- Android之开源项目view篇
本文转自:http://www.trinea.cn/android/android-open-source-projects-view/ 主要介绍Android上那些不错个性化的View,包括List ...
随机推荐
- [转]关于AS3 Socket和TCP不得不说的三两事
磨刀不误砍柴工,让我们从概念入手,逐步深入. 所谓socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄.应用程序通常通过"套接字"向网络 ...
- php正则获取html图片标签信息(采集图片)
php获取html图片标签信息(采集图片),实现图片采集及其他功能,带代码如下: <?php $str="<img src='./a.jpg'/>111111<img ...
- java中接口的定义和接口的实现
1.接口的定义 使用interface来定义一个接口.接口定义同类的定义类似,也是分为接口的声明和接口体,其中接口体由常量定义和方法定义两部分组成.定义接口的基本格式如下: [修饰符] interfa ...
- FK JavaScript之:ArcGIS JavaScript API之地图动画
地图要素动画应用场景:动态显示地图上的要素的属性随着时间的改变而改变,并根据其属性的变化设置其渲染.比如:某水域项目中,随着时间的变化,动态展现水域的清淤进度 本文目的:对ArcGIS JavaScr ...
- ES6(二)解构赋值详解
详解一下之前的解构赋值 ①解构赋值中的"..." let [a,...b]= [1]; b // [] ...代表变量b去匹配剩余的所有元素返回一个数组 ,匹配不到时返回[] // ...
- POMDP
本文转自:http://www.pomdp.org/ 一.Background on POMDPs We assume that the reader is familiar with the val ...
- 球谐光照(Spherical Harmonics Lighting)及其应用-实验篇
简介 之前在一篇实时深度图优化的论文中看到球谐光照(Spherical Harmonics Lighting)的应用,在查阅了许许多多资料之后还是无法完全理解,我个人觉得如果之前对实时渲染技术不是很了 ...
- javascript 数字进制转换
//十进制转其他 var x=110; alert(x); alert(x.toString(8)); alert(x.toString(32)); alert(x.toString(16)); // ...
- sqlite在火狐中安装及使用
1.SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中.它是D.RichardHipp建立的公有领域项目.它的设计目标是嵌入式的,而且目前已经在很多嵌入 ...
- KnocKout 绑定数据
Controller 里面的方法: public ActionResult Index() { return View(); } [HttpPost] public JsonResult Reader ...