Skip to content Skip to sidebar Skip to footer

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 wid

Solution 1:

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.

Solution 2:

Thanks to nhouser9 idea and the documentation https://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html#MATCH_PARENT I have managed to work a solution for this problem. The basic idea is the same, save the initial value so it can be restored after, however first you need to find out whether the view height or width has a fixed or dynamic value and which dynamic value it is, so for my case I have used the following process

int initial_height;
switch (view.getLayoutParams().height) {
    case LayoutParams.MATCH_PARENT:
        initial_height = LayoutParams.MATCH_PARENT;
        break;
    case LayoutParams.WRAP_CONTENT:
        initial_height = LayoutParams.WRAP_CONTENT;
        break;
    default:
        initial_height = view.getLayoutParams().height;
}

But I then understood that the dynamic sizes (match_parent, wrap_content) do have specific values, respectively -1 and -2, according to the documentation, meaning that nhouser9 suggestion worked directly since these dynamic sizes could be acquired directly from the view's dimensions (-1, -2 or positive if fixed size). This means that all that it takes now is to just save the initial size directly, like so

int initial_height = view.getLayoutParams().height;

And that's it. This answer was left here to help anyone looking for the same solution and I will be waiting for the other user to post his answer so that I can choose his as it was his help that got me to the right solution.

Solution 3:

if you want to reset height to Wrap Content :

 ViewGroup.LayoutParams llp = date.getLayoutParams();
                    llp.height= ViewGroup.LayoutParams.WRAP_CONTENT;
                    date.setLayoutParams(llp);

Post a Comment for "How To Reset Or Unset A View Height Or Width Which Were Set Programmatically"