在使用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) 方法时,起始就是在调用以上的方法
/**
* 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);
}
而 layout_width和layout_height 是一个布局的属性,它的含义表示“我在布局中的宽度或者高度”,但是如果仅仅使用layoutInflater加载布局时,最外层的布局文件是没有父布局了,所以它的layout_width和layout_height属性将不起作用了!这样的话我们的解决办法就很简单了,只要在布局文件中添加父布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:layout_width="300dp"
android:layout_height="80dp"
android:text="Button" >
</Button>
</RelativeLayout>
这样我们的布局文件属性就可以起作用了,不管是设置到dialog,还是popuwindow 都可以呈现了!
第二:为什么同样的在setContentView 中就是起作用的,其实在setContentView 中已经默认添加了一个父布局FrameLayout,所以它可以很好的呈现效果