[英]How to know which LayoutParams class to use when creating a View programmatically?
Every ViewGroup
class implements a nested class that extends ViewGroup.LayoutParams
.每个ViewGroup
类都实现了一个扩展ViewGroup.LayoutParams
的嵌套类。 So we LinearLayout.LayoutParams
, RelativeLayout.LayoutParams
, FrameLayout.LayoutParams
etc.所以我们LinearLayout.LayoutParams
, RelativeLayout.LayoutParams
, FrameLayout.LayoutParams
等。
Suppose I want to create a View
, eg TextView
programmatically.假设我想以编程方式创建一个View
,例如TextView
。 I will have to give it the required properties, like layout_width
and layout_height
, for which I will have to use a LayoutParams
class.我必须为其提供所需的属性,例如layout_width
和layout_height
,为此我必须使用LayoutParams
类。 How will I know which LayoutParams
class to use?我如何知道要使用哪个LayoutParams
类?
It depends on what you're putting it into.这取决于你把它放进去。 If you're putting it into a linear layout, use LinearLayout.LayoutParams.如果您要将其放入线性布局,请使用 LinearLayout.LayoutParams。 For relative, use RelativeLayout.LayoutParams.对于相对,请使用 RelativeLayout.LayoutParams。
If you don't know the type- add it first via add, then use getLayoutParams to get it.如果您不知道类型 - 首先通过添加添加它,然后使用 getLayoutParams 获取它。 Then change the layourparams.然后更改layourparams。 When you use the add() that doesn't take a params, the parent will make one for you.当您使用不带参数的 add() 时,父级将为您创建一个。
If you only need view width and height, use a ViewGroup.LayoutParams, as all the other ones inherit from this one.如果您只需要视图宽度和高度,请使用 ViewGroup.LayoutParams,因为所有其他的都继承自这个。 You can assign a ViewGroup.LayoutParams where a RelativeLayout.LayoutParams, LinearLayout.LayoutParams, ... is expected.您可以分配一个 ViewGroup.LayoutParams,其中需要一个 RelativeLayout.LayoutParams、LinearLayout.LayoutParams...。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.