Search code examples
androidandroid-viewandroid-custom-view

Is it a good practice to override `setMeasuredDimension()` or `getMeasuredWidth()` in custom View?


I have a scenario:

ViewA extends ViewB, both override onMeasure() and call setMeasuredDimension(). ViewA sets its width to be 10dp whereas ViewB sets its width to be 20dp. Now if I call super.getMeasuredWidth() from ViewB at the end of onMeasure() to get the width of ViewA, I get 20dp. The reason is obvious when ViewA is done measuring itself, ViewB calls setMeasuredDimension() which in turn overwrite the old values.

Now the obvious solution is to override related methods. My question is, is it a good practice to override setMeasuredDimension() or getMeasuredWidth(), getMeasuredHeight() in custom View.


Solution

  • Silly me, solution was simple. In onMeasure() of ViewB, I collected ViewA's width and height immediately and then called setMeasuredDimension():

    super.onMeasure(wSpec, hSpec);
    final int superWidth = super.getMeasuredWidth();
    final int superHeight = super.getMeasuredHeight();
    setMeasuredDimension(w, h);
    
    // use superWidth and superHeight here
    

    and that's it.