我怎么知道我是否需要调用 setLayoutParams 或只是更改现有 LayoutParams 的值?

How can I know if I need to call setLayoutParams or just change the values of existing LayoutParams?

我怎么知道 getLayotParams() return 是对有效参数的引用还是只是参数的深层副本?

说:

MarginLayoutParams layoutParams = (MarginLayoutParams) getView().getLayoutParams();

layoutParams.leftMargin = horizontalMargin;
layoutParams.rightMargin = horizontalMargin;

够了,还是还需要这条线?

parent.setLayoutParams(layoutParams);

getLayoutParams returns 实际的 LayoutParams,不是深拷贝。但是,更新参数不会触发布局,您必须调用 requestLayout,当您使用 setLayoutParams.

时会自动调用它

因此,如果您想修改值并应用它们,您需要调用 setLayoutParams 或使用 requestLayout.

触发布局

如果你使用 Kotlin,你也可以使用 updateLayoutParams 扩展功能。