I am implementing a custom component in HarmonyOS using Java SDK. In Android to draw a custom view, we override the onDraw method from the View class.
In HarmonyOS the Component class doesn’t have the onDraw method. How to resolve it?
I am implementing a custom component in HarmonyOS using Java SDK. In Android to draw a custom view, we override the onDraw method from the View class.
In HarmonyOS the Component class doesn’t have the onDraw method. How to resolve it?
You can use the onDraw
method by implementing the Component.DrawTask
interface. First you need to call addDrawTask
in the constructor to add a drawing task. The sample code is as follows:
public class MyComponent extends Component implements Component.DrawTask {
public MyComponent(Context context) {
super(context);
addDrawTask(this);
}
@Override
public void onDraw(Component component, Canvas canvas) {
// draw
}
}
You are right, onDraw()
is not available in Component class. But, we have another way to achieve the same functionality. You can implements
Component.DrawTask in your custom component to implement the same functionality. You would need to call addDrawTask in the constructor to add a drawing task.
So, your Custom component code will look like this -
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.app.Context;
import org.jetbrains.annotations.Nullable;
public class CustomComponent extends Component implements Component.DrawTask {
public CustomComponent(Context context, @Nullable AttrSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
addDrawTask(this);
}
@Override
public void onDraw(Component component, Canvas canvas) {
//Do your stuff here
}
}