2

In my project, I want to trigger the implementation in draw() that is present in Element class. In android, we have invalidateSelf to trigger the drawToCanvas(). What is the alternative in HarmonyOS?

animator.addListener(new AnimatorListenerAdapter() {
      @Override
      public void onAnimationRepeat(Animator animation) {
             shiftColor(drawable.getColorMain(), drawable.getColorSub());
             invalidateSelf();
      }
});
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108

2 Answers2

1

According to the team, HarmonyOS does not currently have the alternative for invalidateSelf. But there are plans to support it in the future. Please stay tuned on HarmonyOS official websites.

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
0

As shirley rightly suggested, there is no direct alternative for invalidateSelf() in HarmonyOS to trigger the drawToCanvas() in an Element class.

But, since most of the Element objects will ideally be embedded within a Component object, you can try to acheive this functionality by triggering the drawToCanvas() from the onDraw() function of the Component class (must be implemented with DrawTask interface or create an anonymous inner class on a component object).

Please refer the below two snippets for better understanding on how to trigger the drawToCanvas() in Element class:

public class CustomElement extends Element {
   CustomComponent customComponent;

   public void drawToCanvas(Canvas canvas) {
        .
        .
   }
   
   public void invalidateSelf() {
      customComponent.invalidate();
   }
}

public class CustomComponent extends Component implements Component.DrawTask {

   //initialize this in constructor of the component  
   CustomElement customElement;

   public void onDraw(Component component, Canvas canvas) {
      customElement.drawToCanvas(canvas);
   }

}

Another way is

public class CustomElement extends Element {

   public void drawToCanvas(Canvas canvas) {
        .
        .
   }
}

public class MainAbilitySlice extends AbilitySlice {

   Component mComponent;
   
   public void refreshView() {
      CustomElement customElement = new CustomElement();
      mComponent.setBackground(customElement);
      mComponent.addDrawTask(new Component.DrawTask() {
          @Override
          public void onDraw(Component component, Canvas canvas) {
              customElement.drawToCanvas(canvas);
          }
      });
      mComponent.invalidate();
   }
}
Samuel
  • 36
  • 3