Shadow Shadow - 4 years ago 92
Java Question

How to reset or unset a view height or width which were set programmatically

I am struggling with this and I cannot find a direct answer to this question due to its generic keywords leading the results to unrelated questions.

If I set a view's height or width programmatically, for example:

((Button) findViewById( = 100;

How can I unset/reset/revert this process so the view's height (or width) returns to its default behavior before that size was set?

I am trying to find something like the
Html CSS
equivalent of
height: unset
height: initial
or even the JavaScript way for inline styles

Is there anything to accomplish this in Java/Android Studio?

Answer Source

To solve this problem you should save the height before modifying it. Then when you want to reset it, you can revert to the original height. Luckily, the special cases of MATCH_PARENT and WRAP_CONTENT are represented as integer constants, so this works even for those cases (credit to OP for researching this point).

So, the solution is something like this:

int initial_height = view.getLayoutParams().height;

And then when you want to set the height back to its previous value, just reference the initial_height to do so correctly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download