I know how to set the width and the height of a view using LayoutParams
via doing the following:
android.view.ViewGroup.LayoutParams params = button.getLayoutParams();
params.width = height/7;
params.height = height/10;
button.setLayoutParams(params);
Now, as soon as I wanna apply the same height and the width to another button, I need to create another LayoutParams or overwrite the existing one like here:
android.view.ViewGroup.LayoutParams params2 = but2.getLayoutParams();
params2.width = height/7;
params2.height = height/10;
but2.setLayoutParams(params2);
I have about 50 buttons in my application and I doubt it is considered good code to get all the Params in order to only change the width and the height - I want to keep the remaining params (toLeftOf, [...]).
Is there a way to ONLY change the width and the height of the params but keep the rest of the parameters? So it then looks like something like:
android.view.ViewGroup.LayoutParams params = button.getLayoutParams();
params.width = height/7;
params.height = height/10;
button.setLayoutParams(params);
button2.setLayoutParams(params);
button3.setLayoutParams(params);
butt[...]
Thanks a lot in advance.
In Kotlin we can do it shorter and more elegant:
view.layoutParams = view.layoutParams.apply {
width = LayoutParams.MATCH_PARENT
height = LayoutParams.WRAP_CONTENT
}
If you just want to change one parameter:
view.getLayoutParams().width = 400;
view.requestLayout();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With