4

Welcome. I have a problem. I want to do dynamic wallpaper so that every few seconds to change the text. The program works pretty well because the text is changing, but changing so that the previous text is still visible, and after a few seconds I have a lot of the text. I looked everywhere but I am a beginner and do not know how to solve that problem. There is a code:

private class MyWallpaperEngine extends Engine {  
    private final Handler handler = new Handler();  
    private final Runnable drawRunner = new Runnable() {  
        @Override  
        public void run() {
            draw();  
        }
    };  

    private Paint paint = new Paint();  
    private int width;
    int height;  
    private boolean visible = true;

    public MyWallpaperEngine() {  
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        handler.post(drawRunner);  
    }

    @Override  
    public void onVisibilityChanged(boolean visible) {  
        this.visible = visible;  
        if (visible) {  
            handler.post(drawRunner);  
        } else {  
            handler.removeCallbacks(drawRunner);  
        }
    }

    @Override  
    public void onSurfaceDestroyed(SurfaceHolder holder) {  
        super.onSurfaceDestroyed(holder);  
        this.visible = false;  
        handler.removeCallbacks(drawRunner);  
    }  

    @Override  
    public void onSurfaceChanged(SurfaceHolder holder, int format,  
            int width, int height) {  
        this.width = width;  
        this.height = height;  
        super.onSurfaceChanged(holder, format, width, height);  
    }  

    private void draw() {  
        SurfaceHolder holder = getSurfaceHolder();  
        Canvas canvas = null;
        try {  
            canvas = holder.lockCanvas();  
            if (canvas != null)
                drawAnimation(canvas);

        } finally {
            if (canvas != null)
                holder.unlockCanvasAndPost(canvas);

        }
        if (visible) {
            handler.postDelayed(drawRunner, 4000);  
        }
    }
    private void drawAnimation(Canvas c){
        Random r = new Random();
        int i1=r.nextInt(200-50) + 50;
        String text = Integer.toString(i1);
        c.drawText(text, i1, i1, paint);
    }
}  
Dr Glass
  • 1,487
  • 1
  • 18
  • 34

1 Answers1

2

You should clear the canvas before drawing, using something like

c.drawColor(int color);

or draw anything else that covers the entire area, otherwise you will just draw onto what was already on the canvas.

Jave
  • 31,598
  • 14
  • 77
  • 90