Search code examples
androidlayoutviewwidthonmeasure

How to get custom View's width when layout_width is wrap_content?


Let's say we have our custom View declared in XML and we override its onMeasure() method:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    // Maximal length of line is width of this View 
    width = this.getLayoutParams().width;

If XML attribute android:layout_width="100px" is set then width returns value 100. But if attribute is android:layout_width="match_parent" or android:layout_width="wrap_content" then it returns -1 or -2. So how can we get measured width of this View in this case?


Solution

  • Use

    width = MeasureSpec.getSize(widthMeasureSpec);