Android OS 中的 onMeasure 在鸿蒙 OS 中的替代功能是什么?

问题描述

我正在使用 Java SDK 在 HarmonyOS 中编写自定义组件。 为了在 Android 中协商自定义视图的宽度和高度,我们覆盖了 onMeasure()

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

HarmonyOS 上面的替代方案是什么?

解决方法

在 Android 中 - enter image description hereonMeasure() 类中可用的受保护方法,因此可以通过扩展 View 类直接在自定义组件中覆盖它。

对于 HarmonyOS 中的替代方案 - 您必须在自定义组件中实现 View,然后在覆盖函数 Component.EstimateSizeListener 中写下实现。

所以在 Android 中,当你有一些这样的代码时 -

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 的变化将是 -

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) {
   }
}