What's happening is it gets input from the user via touch, then get X and Y, then draw a circle on that coordinate. There were no flickering if I just draw a dot (or just tap the screen). But when I drag the mouse and draw a line, I starts to flicker. It seems that some of the drawings are drawn in the back buffer and some are drawn in the front buffer.
How can I avoid the flickering of the graphics, or how make the front and back buffer have the same drawings?
GIF related. Animation of what is happening when I draw (stroke).

The Main Activity
- Code: Select all
package com.gsample;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new Panel(this));
}
}
The Panel
- Code: Select all
package com.gsample;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
class Panel extends SurfaceView implements SurfaceHolder.Callback {
private TutorialThread thread;
public int x = 100;
public int y = 100;
private Paint paint;
public Panel(Context context) {
super(context);
paint = new Paint();
paint.setColor(Color.WHITE);
getHolder().addCallback(this);
thread = new TutorialThread(getHolder(), this);
setFocusable(true);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO
}
public void surfaceCreated(SurfaceHolder holder) {
thread.setRunning(true);
thread.start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// try and try until the thread die
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
x = (int)event.getX();
y = (int)event.getY();
return true;
}
public void paint(Canvas canvas) {
canvas.drawCircle(x, y, 5, paint);
}
}
The Thread
- Code: Select all
package com.gsample;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
class TutorialThread extends Thread {
private SurfaceHolder surfaceHolder;
private Panel panel;
private boolean run = false;
public TutorialThread(SurfaceHolder holder, Panel panel) {
surfaceHolder = holder;
this.panel = panel;
}
public void setRunning(boolean run) {
this.run = run;
}
@Override
public void run() {
Canvas c = null;
while (run) {
c = null;
try {
c = surfaceHolder.lockCanvas(null);
synchronized(surfaceHolder) {
panel.paint(c);
}
} finally {
if (c != null) {
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}

