I have designed an layout in which LinearLayout
has 2 children LinearLayout
and FrameLayout
and in each child I put different views.
In Kotlin you can simply do this:
fr.post {
height=fr.height
width=fr.width
}
just give your height and You will get height or even width if wanted.
/** * Get the view height before the view will render * @param view the view to measure * @return the height of the view */
public static int getViewHeight(View view) {
WindowManager wm =
(WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int deviceWidth;
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2){
Point size = new Point();
display.getSize(size);
deviceWidth = size.x;
} else {
deviceWidth = display.getWidth();
}
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(deviceWidth, View.MeasureSpec.AT_MOST);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthMeasureSpec, heightMeasureSpec);
return view.getMeasuredHeight(); // view.getMeasuredWidth();
}
Most easiest way is to use ViewTreeObserver, if you directly use .height or .width you get values as 0, due to views are not have size until they draw on our screen. Following example will show how to use ViewTreeObserver
ViewTreeObserver viewTreeObserver = YOUR_VIEW_TO_MEASURE.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
YOUR_VIEW_TO_MEASURE.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int viewHeight = YOUR_VIEW_TO_MEASURE.getHeight();
int viewWeight = YOUR_VIEW_TO_MEASURE.getWidth();
}
});
}
if you need to use this on method, use like this and to save the values you can use globle variables.
As I just ran into this problem thought I would write it for kotlin,
my_view.viewTreeObserver.addOnGlobalLayoutListener {
// here your view is measured
// get height using my_view.height
// get width using my_view.width
}
or
my_view.post {
// here your view is measured
// get height using my_view.height
// get width using my_view.width
}
For frame:
height=fr.getHeight();
width=fr.getWidth();
For screen:
width = getWindowManager().getDefaultDisplay().getWidth();
height = getWindowManager().getDefaultDisplay().getHeight();
Just wanted to add an answer here, since Koltin has some convenience methods to do this, which are a lot less ugly than adding and removing a onGlobalLayoutListener
:
view.doOnLayout {
it.measuredWidth
it.measuredHeight
}
You can see more of the convinience methods here.