How to dynamically set the width and height of a control in Android?

In Android, you can dynamically set the width and height of a widget using code. Here is an example code that demonstrates how to dynamically set the width and height of a Button widget:

Button button = findViewById(R.id.button);

// 设置宽度为200像素
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(200, ViewGroup.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(layoutParams);

// 设置高度为100像素
button.getLayoutParams().height = 100;

In the example above, we first obtain an instance of the Button control through findViewById, then create a LayoutParams object, set the width to 200 pixels, and the height to wrap content. Finally, we apply the LayoutParams to the Button control using the setLayoutParams method. Alternatively, we can also directly access the original LayoutParams object by using the getLayoutParams method, and then set the width and height properties directly.

It is important to note that dynamically adjusting the width and height of a control may affect its layout and display effects, so careful consideration is required when setting it.

bannerAds