1

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

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

HarmonyOS 中上述内容的替代方法是什么?

4

1 回答 1

1

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

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

所以在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 代码更改将是 -

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) {
   }
}
于 2021-07-26T05:51:10.120 回答