Search code examples
xamarinxamarin.android

Blinking Button Xamarin Android


How can I make the button have the animation of blinking?

I want to add it while waiting to retrieve the location of the user, but I cannot see any example.

What I have done now is only changing the background then change it again after retrieving the location.

button.SetBackgroundColor(new Color(ContextCompat.GetColor(this.Context, Resource.Color.primaryColor)));


Solution

  • Normally I'd say use Xamarin's Animation class, but you're not asking for any gradual transitions. I would then use System.Threading.Timer:

    private readonly Timer _blinkTimer;
    

    Then in your constructor:

    _blinkTimer= new Timer(BlinkTimerCallback);
    

    Create the BlinkTimerCallback method:

    private void BlinkTimerCallback(object state)
    {
        // This is sudo code - I don't know the proper syntax off the top of my head
        if(button.BackgroundColor == red)
        {
            button.SetBackgroundColor(gray);
        }
        else
        {
            button.SetBackgroundColor(red);
        }
    }
    

    Then you just switch the timer off or on based on state:

    To switch it on:

    _blinkTimer.Change(new TimeSpan(0, 0, 1), new TimeSpan(0, 0, 1));
    

    To switch it off:

    _blinkTimer.Change(Timeout.Infinite, Timeout.Infinite);