Skip to content Skip to sidebar Skip to footer

How To Change Color Of Canvas In Android Dynamically For Every 5 Sec.?

I am creating an android application that consists of canvas to draw circles and canvas color will be changed for every 5 seconds.Here's the code what i did but it does not changed

Solution 1:

Try this code. I have made some changes to your code using Handlers. this will give you an basic idea.

publicclassAutomode_ActivityextendsActivity {


    Thread timer;
     boolean Count=true;
    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(newMyView(this));




    }
    publicclassMyViewextendsView{

    Runnable runnable= newRunnable() {

    publicvoidrun() {
      this.invalidate();
    }
    };

    Handlerhandler=newHandler();

    publicMyView(Context context) {
            super(context);

    }
    @OverrideprotectedvoidonDraw(final Canvas canvas) {
            super.onDraw(canvas);


            getWidth();
            getHeight();
            finalintradius=25;
            System.currentTimeMillis();

            finalPaintpaint=newPaint();
            paint.setStyle(Paint.Style.FILL);

            canvas.drawPaint(paint);

            if(Count)  
             {
               paint.setColor(Color.parseColor("#D50000"));
             }                
             else
             {
              paint.setColor(Color.parseColor("#33691E"));
             }   
             Count=!Count;   

            canvas.drawCircle(300, 300, radius, paint);
            canvas.drawCircle(400, 300, radius, paint);
            canvas.drawCircle(500, 300, radius, paint);
            canvas.drawCircle(600, 300, radius, paint);
            canvas.drawCircle(700, 300, radius, paint);
            canvas.drawCircle(800, 300, radius, paint);
            canvas.drawCircle(900, 300, radius, paint);
            handler.postDelayed(runnable, 5000);
                }
        }
}

Solution 2:

Well, all you got just messed-up:

  1. Try to not initialize anything in onDraw() - this method is calls every time you redraw your view.

  2. You've messed-up with colors here - you're drawing circles with paint but you're changing paint1 in your thread.

  3. I don't understand why do you call all this getWidth()getHeight() and System.currentTimeMillis()

So, I've cleaned a little bit all of your code and optimized it. That's how it should work now:

publicclassMainActivityextendsActivity {

    private MyView view;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = newMyView(this);
        setContentView(view);
    }

    @OverrideprotectedvoidonStart() {
        // Restart view thread
        view.startChangingColors(5000);
        super.onStart();
    }

    @OverrideprotectedvoidonStop() {
        // Stopping thread
        view.stopRunnning();
        super.onStop();
    }

    publicclassMyViewextendsView {

        private Thread colorThread;

        privatefinalintcolor1= Color.parseColor("#D50000");
        privatefinalintcolor2= Color.parseColor("#33691E");

        private Paint paint;
        private Paint clearingPaint;

        privatefinalintradius=25;

        privatebooleanswitcher=true;

        publicMyView(Context context) {
            super(context);

            // Init goes here
            paint = newPaint();
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(color1);

            clearingPaint = newPaint();
            clearingPaint.setStyle(Paint.Style.FILL);
            clearingPaint.setColor(Color.WHITE);

            // Run thread
            startChangingColors(5000);
        }

        publicvoidstopRunnning() {
            // Stopping previous threadif (colorThread != null) {
                colorThread.interrupt();
            }
        }

        /**
         * Starting a thread that changes colors every n miliseconds
         * 
         * @param delay
         */publicvoidstartChangingColors(finalint delayMilis) {
            // Hust a safety check
            stopRunnning();

            colorThread = newThread(newRunnable() {

                @Overridepublicvoidrun() {
                    booleaninterrupted=false;
                    while (!interrupted) {
                        try {
                            runOnUiThread(newRunnable() {

                                @Overridepublicvoidrun() {
                                    changeColors();
                                }
                            });

                            Thread.sleep(delayMilis);

                        } catch (Exception e) {
                            if (e instanceof InterruptedException) {
                                // We just woked up to close all this
                                interrupted = true;
                            } else {
                                Log.e("Error:", e.getMessage());
                            }
                        }
                    }

                }
            });
            colorThread.start();
        }

        publicvoidchangeColors() {
            if (switcher) {
                paint.setColor(color1);
            } else {
                paint.setColor(color2);
            }
            switcher = !switcher;
            // Redraw view
            invalidate();
        }

        @OverrideprotectedvoidonDraw(final Canvas canvas) {
            // Clear the canvas
            canvas.drawPaint(clearingPaint);
            // Draw circles
            canvas.drawCircle(300, 300, radius, paint);
            canvas.drawCircle(400, 300, radius, paint);
            canvas.drawCircle(500, 300, radius, paint);
            canvas.drawCircle(600, 300, radius, paint);
            canvas.drawCircle(700, 300, radius, paint);
            canvas.drawCircle(800, 300, radius, paint);
            canvas.drawCircle(900, 300, radius, paint);
        }
    }
}

Solution 3:

// define boolean to change color after 5000 msboolean change = false;

// prepare runnable which will be called after 5000 ms // through handlerRunnable mRunnable = newRunnable() {

  publicvoidrun() {

    change_color(change);
    change = !change;

  }


};

// create handler Handler mHandler = newHandler();
mHandler.postDelayed(mRunnable, 5000);

// use receivedChange variable in change_colors() // and change canvas color based on thatprivatevoidchange_colors(boolean receivedChange) {

        runOnUiThread(newRunnable() {

            @Overridepublicvoidrun() {

                if(receivedChange == true) {
                    paint1.setColor(Color.parseColor("#D50000"));
                } else {
                    paint1.setColor(Color.parseColor("#33691E"));
                }   

                    canvas.drawCircle(300, 300, radius, paint1);
                    canvas.drawCircle(400, 300, radius, paint1);
                    canvas.drawCircle(500, 300, radius, paint1);
                    canvas.drawCircle(600, 300, radius, paint1);
                    canvas.drawCircle(700, 300, radius, paint1);
                    canvas.drawCircle(800, 300, radius, paint1);
                    canvas.drawCircle(900, 300, radius, paint1);
                }
            });

Post a Comment for "How To Change Color Of Canvas In Android Dynamically For Every 5 Sec.?"