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.
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:
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:
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.
Try something like this :
You are probobly calling
getHeight()
to early. Ensure thatgetParent().getHeight()
is being called afterviewGroup.addView(view0)
and/orsetContentView(activity_main.xml)
. This has happened to me in the past and this fixed it.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?
One alternative to programmatically implement this is to use following method:
By the time this method is invoked, the layouting-process has been finished. Thus you can obtain the parent attributes correctly.
As Example:
In
OnCreate()
method ,if you uselayout.getHeight()
andlayout.getWidth()
, it will returns 0, instead you can follow this: