android LayoutInflater加载的布局大小不受控制

在使用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,所以它可以很好的呈现效果


  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值