Android 以编程方式更改大小

Android change size programmatically

我需要以编程方式更改按钮的大小。 我阅读了一些答案,然后执行下一步更改按钮大小。

button.setLayoutParams(new RelativeLayout.LayoutParams(150, 50));

此代码可以正确更改大小,但问题是按钮没有停留在我想要的位置,它将按钮移动到左上角。

我需要更改按钮大小但我不想更改位置。

我该如何解决这个问题?

您还必须使用现有的 RelativeLayout 规则,即项目是否居中对齐、父级左对齐等。或者您可以使用现有的 Params 并修改宽度和高度,如下所示 RelativeLayout 规则将不可修改。

  RelativeLayout.LayoutParams layoutParams= (RelativeLayout.LayoutParams) button.getLayoutParams();
        layoutParams.width=150;
        layoutParams.height=50;
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) button.getLayoutParams();
params.width = 500;
params.height = 500;
button.setLayoutParams(params);