tags:

views:

188

answers:

2

I want to determine the available height and width of the parent layout to which I have to add my view.

I have used many methods on layout like

  • layout.getHeight()
  • layout.getRootView().getHeight()

All these methods return 0(zero) as the result.

My main requirement is to be able to give width to a view that is some % of the width of the layout .

Also I dont want to use tag for this. I want to do it through code.

Thanks in advance.

+1  A: 

The issue here is you are trying to get the parent height/weight before the layoutmanager completes parent layout. You can only get parent dimensions, after its layout is complete.

The recommended way to do what you want to achieve is by using layout_weight field of LayoutParams. link text

In particular you should use:

LayoutParams lp = new LinearLayout.LayoutParams(width, height,
weight);

layout_weight value can be anything between 0.0 to 1.0. So for example if I have myButton within parentLayout, and I want myButton to occupy 30% of parent layout...I would use something like:

 myButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                                               LayoutParams.WRAP_CONTENT,0.3));

The layout_weight sum of all child elements should be 1. Also, layout_weight should not be used with view's width or height set to LayoutParams.FILL_PARENT.

Megha Joshi
But how do I get the the height and width of the parent layout. ........... LayoutParams lp = new LinearLayout.LayoutParams(width, height,weight); ......... To give height in % this method is only useful If I have parent layouts height and width
Robin
No, you dont need to know the exact width/height of parent for using this method. You can specify anything between 0 to 1 as a weight. So for example if I have myButton within parentLayout, and I want myButton to occupy 30% of parent layout...I would use something like:
Megha Joshi
sorry comment space didnt suffice...I edited my answer above.
Megha Joshi
Thanks for the reply Megha. My requirement is that I want to show an Image view in a linearlayout which has width same as that of linear layout and height should be variable.
Robin
Image view has this method ............setLayoutParams(ViewGroup.LayoutParams params) ........ This takes an argument of type ViewGroup.LayoutParams and this class has no such constructor which takes layout_width
Robin
Actually the sizes of my images are small.. but I want my images to stretch and use the entire width of screen
Robin
A: 

Ok. I found a solution to it. The way we can get hieght of the screen in activity is

getApplicationContext().getResources().getDisplayMetrics().heightPixels

But I still dont know how to get the pixel dimentions of parent layout?

Robin