I have designed an layout in which LinearLayout
has 2 children LinearLayout
and FrameLayout
and in each child I put different views.
I think you are getting Height and Width in OnCreate() method that's why you getting always 0 values because at that time your view still not created.
Try to get height and width on some button click or else..
If you get -1 or -2 it could also be the numeric value of LayoutParams.WRAP_CONTENT (-2) or LayoutParams.MATCH_PARENT (-1).
The view itself, has it's own life cycle which is basically as follows:
Attached
Measured
Layout
Draw
So, depending on when are you trying to get the width/height you might not see what you expect to see, for example, if you are doing it during onCreate, the view might not even been measured by that time, on the other hand if you do so during onClick method of a button, chances are that by far that view has been attached, measured, layout, and drawn, so, you will see the expected value, you should implement a ViewTreeObserver to make sure you are getting the values at the proper moment.
LinearLayout layout = (LinearLayout)findViewById(R.id.YOUD VIEW ID);
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
this.layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
int width = layout.getMeasuredWidth();
int height = layout.getMeasuredHeight();
}
});
The first snippet is correct, but you need to call it after onMeasure()
gets executed. Otherwise the size is not yet measured for the view.