How to call onDraw(Canvas canvas) function of CustomView in Android?

562 Views Asked by At

I generate an ellipse and I try to reshape with respect to sweepAngle_speed that u can see below. This sweepAngle_speed come from MainActivity.java. In MainActivity.java, I create a seekbar and I use an algorithm between value of seekbar and sweepAngle_speed, therefore I expected a change in filled area in my ellipse. onDraw function is not called directly, so I use invalidate function in my getLog function which is created by me. However I cannot call onDraw function anyway. When I run the code, onDraw function is called directly by system 3 times, however when I change seekbar value, I do not call onDraw function anyway. My first question is that How onDraw function is called directly by system ? The second one is how I can call onDraw function during system is working. Thanks.

CustomView.java

public CustomView(Context context, @Nullable AttributeSet attrs) {
    super(context);
    m_Context = context;
    getLog();
    // create the Paint and set its color
}``


@Override
protected void onDraw(Canvas canvas) {
    //c=canvas;
    //super.onDraw(c);
    Paint p1 = new Paint();
    RectF rectF = new RectF(-750, 0, 750, 720);
    //p1.setColor(Color.parseColor("#34ebe2"));
    p1.setShader(new LinearGradient(0, -360, 0, getHeight(), Color.CYAN, Color.BLUE, Shader.TileMode.MIRROR));
    Log.d(TAG, "CANVAS: onDraw içine girdi ve Speed angle: " + sweepAngle_speed);
    canvas.drawArc(rectF, 90, -sweepAngle_speed, true, p1);
}


public void getLog () {
    paint = new Paint();
    paint.setColor(Color.BLUE);
    Log.d(TAG, "Speed geldi buraya ve invalidate yaptı");
    setWillNotDraw(false);
    //this.invalidate();
    this.invalidate();
}

}

2

There are 2 best solutions below

0
On

If you extend ViewGroup so you need to call setWillNotDraw(false) in the constructor of your ViewGroup

3
On

You can't call onDraw directly. You can use the invalidate method which will redraw it

You can make a function inside CustomView class e.g:

public void setSpeed(int sweepAngle_speed){
    this. sweepAngle_speed = sweepAngle_speed;
    invalidate();  // This invalidate will call onDraw and draw your view again
}