【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等,否则运行的时候会抛出异常的。

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

    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);

    view.setLayoutParams(layoutParams);

你可能感兴趣的:(android,UI)