【Android】不知道的 setLayoutParams

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

  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能够随意设置。this

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

    <!-- lang: java -->文档

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

    <!-- lang: java -->class

    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);sso

    <!-- lang: java -->layout

    view.setLayoutParams(layoutParams);异常

相关文章
相关标签/搜索