Home > Software design >  How to change button color when it is clicked in Xamarin
How to change button color when it is clicked in Xamarin

Time:03-22

I am quite new in xamarin and I am trying to add a click events to my buttons. So here are my 4 buttons:

<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
                    <Button Text="Page 1" TextColor="#EEF2FF" FontSize="20" HorizontalOptions="Center" BackgroundColor="#FF5959" />
                </StackLayout>
                <StackLayout Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center">
                    <Button Text="Page 2" Clicked="Handle_Page" TextColor="#676FA3" FontSize="20" HorizontalOptions="Center" BackgroundColor="#EEF2FF"/>
                </StackLayout>
                <StackLayout Grid.Column="2" HorizontalOptions="Center" VerticalOptions="Center">
                    <Button Text="Page 3" TextColor="#676FA3" FontSize="20" HorizontalOptions="Center" BackgroundColor="#EEF2FF"/>
                </StackLayout>
                <StackLayout Grid.Column="3" HorizontalOptions="Center" VerticalOptions="Center">
                    <Button Text="Page 4" TextColor="#676FA3" FontSize="20" HorizontalOptions="Center" BackgroundColor="#EEF2FF"/>
                </StackLayout>

So the colour of the buttons are #EEF2FF but when I click on the button I want it to be changed to #FF5959. But if there is another button clicked already, then it should also change to the main colour, #EEF2FF. So we can cay synchronized click event.

I am quite new, so any help would be appreciated.

CodePudding user response:

add a clicked handler

<Button Clicked="ButtonClicked" ... />

then in the handler

protected void ButtonClicked(object sender, EventArgs args)
{
  // set the other buttons back to the base color
  // you will need to assign each button an x:Name in xaml
  btn1.BackgroundColor = Color.FromHex("EEF2FF");
  ...
  btn10.BackgroundColor = Color.FromHex("EEF2FF");

  // then change the color of only the selected button
  var btn = (Button)sender;
  btn.BackgroundColor = Color.FromHex("FF5959");
} 

CodePudding user response:

protected override void OnCreate(Bundle savedInstanceState)
{   
    ScreenClickButton.Click  = ChangeColorToRed;
}

private void ChangeColorToRed(object sender, EventArgs e)
{
    ScreenClickButton.SetBackgroundColor(color: Color.Red);
}
  • Related