Question

Im having problems specifiying the height of a relative Layout. From what i understand, these two blocks of code should be equivalent (myLayout is a RelativeLayout that i defined in XML, with an initial height of "0dp", and it's parent is also a RelativeLayout):

BLOCK 1:

RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams)myLayout.getLayoutParams();
p.height = (int)(35*scale);
myLayout.setLayoutParams(p);
myLayout.invalidate();

BLOCK 2:

RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams)myLayout.getLayoutParams();
RelativeLayout.LayoutParams newP = new RelativeLayout.LayoutParams(p.width, (int)(35*scale));
myLayout.setLayoutParams(newP);
myLayout.invalidate();

Scale, in my case, is 2. So i expect myLayout to have a height of 70 after the execution of either of these blocks, and i expect it to return that height when i call myLayout.getHeight(). Also, i expect myLayout to occupy a rect with the height of 70 and its former width (happens to be match_parent).

But when i run the code, the first block does not change the height of myLayout on screen, nor does it change the return value of myLayout.getHeight(). It does, however, change myLayout.getLayoutParams().height.

Now the second block does work, although i have to run it twice(!?) for the change to take effect. Im seriously at a loss here and i cant find anything even closely related to this in the docs.

I thought this would be an easy task when i set out yesterday, but by now im questioning my sanity, among other things. Any Ideas?

Was it helpful?

Solution

If size is determined dynamically, you may need to use ViewTreeObserver to get the size seen on the screen.

Set your width and height in defining your params. If you want the width to be match_parent, change your code like below and it is going to work (if you don't want match_parent, just set the width that you desire in the code below):

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                           LayoutParams.MATCH_PARENT, (int)(35*scale));
myLayout.setLayoutParams(params);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top