【问题标题】:How to know which LayoutParams class to use when creating a View programmatically?以编程方式创建视图时如何知道要使用哪个 LayoutParams 类?
【发布时间】:2016-03-18 17:07:41
【问题描述】:
每个ViewGroup 类都实现了一个扩展ViewGroup.LayoutParams 的嵌套类。所以我们LinearLayout.LayoutParams、RelativeLayout.LayoutParams、FrameLayout.LayoutParams等。
假设我想创建一个View,例如TextView 以编程方式。我必须给它必需的属性,比如layout_width和layout_height,为此我必须使用LayoutParams类。我怎么知道要使用哪个 LayoutParams 类?
【问题讨论】:
标签:
android
android-layout
android-linearlayout
android-view
android-layoutparams
【解决方案1】:
这取决于您将其放入的内容。如果要将其放入线性布局,请使用 LinearLayout.LayoutParams。对于相对,请使用 RelativeLayout.LayoutParams。
如果你不知道类型 - 先通过 add 添加,然后使用 getLayoutParams 获取。然后更改layourparams。当您使用不带参数的 add() 时,父级会为您制作一个。
【解决方案2】:
如果您只需要视图的宽度和高度,请使用 ViewGroup.LayoutParams,因为所有其他的都继承自这个。您可以分配一个 ViewGroup.LayoutParams,其中需要一个 RelativeLayout.LayoutParams、LinearLayout.LayoutParams、...。