mInflater.inflate(R.layout.item_express, null); 高度失效

来源:互联网 发布:淘宝天猫优惠券好做吗 编辑:程序博客网 时间:2024/05/23 19:43
最近在做dialog时候,发现用这个参数高度失效, 后来分析了下, 看了别人的分析,改为

convertView = mInflater.inflate(R.layout.item_express, parent,false);

问题解决:以下是参考文档

在使用LayoutInflater 加载布局时,经常会碰到这样的情况,明明在布局里设置了布局的大小,为什么就是不起作用,但是同样的布局 在setContentView() 中就可以起作用呢!在查看底层LayoutInflater 中的inflate 方法中终于找到了答案!

首先 我们来看 inflate(int resource, ViewGroup root, boolean attachToRoot) 方法中其他两个参数的含义:

 

1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。

2. 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。

3. 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。

4. 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。


而我们在调用 inflate(int resource, ViewGroup root) 方法时,起始就是在调用以上的方法

[java] view plain copy
  1. /** 
  2.      * Inflate a new view hierarchy from the specified xml resource. Throws 
  3.      * {@link InflateException} if there is an error. 
  4.      *  
  5.      * @param resource ID for an XML layout resource to load (e.g., 
  6.      *        <code>R.layout.main_page</code>) 
  7.      * @param root Optional view to be the parent of the generated hierarchy. 
  8.      * @return The root View of the inflated hierarchy. If root was supplied, 
  9.      *         this is the root View; otherwise it is the root of the inflated 
  10.      *         XML file. 
  11.      */  
  12.     public View inflate(int resource, ViewGroup root) {  
  13.         return inflate(resource, root, root != null);  
  14.     }  
而 layout_width和layout_height 是一个布局的属性,它的含义表示“我在布局中的宽度或者高度”,但是如果仅仅使用layoutInflater加载布局时,最外层的布局文件是没有父布局了,所以它的layout_width和layout_height属性将不起作用了!这样的话我们的解决办法就很简单了,只要在布局文件中添加父布局:

[java] view plain copy
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  2.     android:layout_width="match_parent"    
  3.     android:layout_height="match_parent" >    
  4.     
  5.     <Button    
  6.         android:layout_width="300dp"    
  7.         android:layout_height="80dp"    
  8.         android:text="Button" >    
  9.     </Button>    
  10.     
  11. </RelativeLayout>    
这样我们的布局文件属性就可以起作用了,不管是设置到dialog,还是popuwindow 都可以呈现了!

第二:为什么同样的在setContentView 中就是起作用的,其实在setContentView 中已经默认添加了一个父布局FrameLayout,所以它可以很好的呈现效果



阅读全文
0 0