【Android】不知道的 setLayoutParams

动态创建Layout的时候,LayoutParams 是必须要设置的参数,关于 setLayoutParams 知道多少呢?

  1. setLayoutParams 是设给父节点的。 文档里说的清楚:

Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.

也就是说这个setLayoutParams()是给其父控件看的,只有父类可以改变子View的位置布局,而不是说子View可以随意设置。

  1. setLayoutParams 类型不能随便给。 清楚了LayoutParams是根据父节点来设置的,虽然使用的时候创建一个 ViewGroup.LayoutParams 也能够设置成功,但还是要根据父节点的类型来定义为具体的 RelativeLayout.LayoutParams、LinearLayout.LayoutParams等,否则运行的时候会抛出异常的。

    <!-- lang: java -->

    RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

    <!-- lang: java -->

    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);

    <!-- lang: java -->

    view.setLayoutParams(layoutParams);

转载于:https://my.oschina.net/giszhang/blog/323075

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值