Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Layout Params change ONLY width and height

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.

like image 346
user2875404 Avatar asked Feb 02 '15 01:02

user2875404


2 Answers

In Kotlin we can do it shorter and more elegant:

view.layoutParams = view.layoutParams.apply {
    width = LayoutParams.MATCH_PARENT
    height = LayoutParams.WRAP_CONTENT
}
like image 177
Pavel Shorokhov Avatar answered Sep 28 '22 04:09

Pavel Shorokhov


If you just want to change one parameter:

view.getLayoutParams().width = 400;
view.requestLayout();
like image 33
M. Usman Khan Avatar answered Sep 28 '22 05:09

M. Usman Khan