javaandroidhuawei-mobile-serviceshuawei-developersharmonyos

What is the alternative function in HarmonyOS for onMeasure in Android OS?


I am writing a custom component in HarmonyOS using Java SDK. In order to negotiate the width and height of the custom view in Android, we override onMeasure().

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

What is the alternative for the above in HarmonyOS?


Solution

  • In Android - onMeasure() is a protected method available in View class so one can directly override it in custom component by extending the View class.

    For alternative in HarmonyOS - you will have to implement Component.EstimateSizeListener in your custom component and then write down the implementation in overriden function onEstimateSize.

    So in Android, when you have some code like this -

    public class CustomView extends View {
    
       public CustomView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
       }
    
       @Override
       protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
       }
    }
    
    

    Harmony Code changes will be -

    public class CustomComponent implements ComponentContainer.EstimateSizeListener
    
    public CustomComponent(Context context, AttrSet attrSet, String styleName) {
           super(context, attrSet, styleName);
           setEstimateSizeListener(this); //set the listener here
       }
    
       @Override
       public boolean onEstimateSize(int widthEstimatedConfig, int heightEstimatedConfig) {
       }
    }