Ruslan Ver
Ruslan Ver

Reputation: 137

color button C# Xamarin Android

I'm building a trivia application so i want when i press the button it will be Green if correct and will be Red if not. my main issue is that wehen i color the button he get larger and looses his grpahic shape.

private void Button2_Click(object sender, EventArgs e)
    {
        if (answer == "ב")
        {
            Button2.SetBackgroundColor(Android.Graphics.Color.Green);
        }
        else
        {
            Button2.SetBackgroundColor(Android.Graphics.Color.Red);
        }
    }

before button pressing after button pressing

thanks for helping!

Upvotes: 2

Views: 5455

Answers (1)

pinedax
pinedax

Reputation: 9346

Try this:

Button2.Background.SetColorFilter (Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Multiply);

Actually the button is not getting bigger as it seems is just that the default drawable for the button in Android has paddings, once you change the background setting your color you are removing those and the button is showing its full size.

For Android API 21+ you can also use the Button2.Background.SetTint(); method.

UPDATE

To set the previous ColorFilter

var previous = Button2.Background.ColorFilter;

 // Set new color
Button2.Background.SetColorFilter (Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Multiply);

...
...
//Do all you need to do and when ready to set it back

Button2.Background.SetColorFilter(previous);

UPDATE 2

If you want to set it back after certain time you can use this code:

private async void Button2_Click (object sender, EventArgs e)
{
    var previous = Button2.Background.ColorFilter;

    if (answer == "ב")
    {
        Button2.Background.SetColorFilter (Android.Graphics.Color.Green, Android.Graphics.PorterDuff.Mode.Multiply);
    }
    else
    {
        Button2.Background.SetColorFilter (Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply);
    }

    // This will await 2 seconds before setting the original color.
    await Task.Delay (2000);

   // Using this so we are sure it will run in the UI thread.
    RunOnUiThread (() => {
        Button2.Background.SetColorFilter (previous);
        });
}

Upvotes: 2

Related Questions