Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent Width and Height

Tags:

android

layout

I've create a custom view based on LinearLayout and I need to calculate the layout width and height according to the parent view but each time I use ((View)this.getParent()).getMeasuredWidth() I got 0 - I guess that I called this function too early!

Any ideas to how accomplish this functionality?

like image 892
iSun Avatar asked Dec 21 '13 12:12

iSun


2 Answers

try this

ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
  viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
      view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
      viewWidth = view.getParent().getWidth();
      viewHeight = view.getParent().getHeight();
    }
  });
}
like image 81
Hardik Avatar answered Sep 30 '22 20:09

Hardik


in Kotlin you can use like this :

   val height = (parent as View).height
like image 31
Sana Ebadi Avatar answered Sep 30 '22 19:09

Sana Ebadi