如何知道在以编程方式创建视图时要使用哪个 LayoutParams class?

How to know which LayoutParams class to use when creating a View programmatically?

每个 ViewGroup class 实现一个扩展 ViewGroup.LayoutParams 的嵌套 class。所以我们 LinearLayout.LayoutParamsRelativeLayout.LayoutParamsFrameLayout.LayoutParams

假设我想创建一个 View,例如TextView 以编程方式。我必须给它 必需的 属性,例如 layout_widthlayout_height,为此我必须使用 LayoutParams class.我如何知道要使用哪个 LayoutParams class?

这取决于您将其放入的内容。如果将其放入线性布局,请使用 LinearLayout.LayoutParams。对于相对,使用 RelativeLayout.LayoutParams.

如果您不知道类型 - 先通过添加添加它,然后使用 getLayoutParams 获取它。然后改变layourparams。当您使用不带参数的 add() 时,父级将为您制作一个。

如果您只需要视图的宽度和高度,请使用 ViewGroup.LayoutParams,因为所有其他的都继承自此。您可以分配 ViewGroup.LayoutParams,其中 RelativeLayout.LayoutParams、LinearLayout.LayoutParams、... 是预期的。