locked
How to dynamically change background color with button? RRS feed

  • Question

  • User398284 posted

    Hi All,

    How do I code a button to dynamically change the Stack layout background color on my xamarin Android app? I currently only have a single view and an empty event handler for when the button is clicked. I would like the user to click the button and have the background change color. When the button is clicked again, I would like the button to return to its original color.

    Thanks.

    Friday, December 4, 2020 3:44 AM

Answers

  • User371688 posted

    You can define a globle variabe as follows:

         bool flag = true;
    

    And when we click the button, we can change the background color acccording to the value of this variable.

        private void Button_Clicked(object sender, EventArgs e)
        {
    
            if (flag)
            {
                stack_layout.BackgroundColor = Color.Green;
                flag = false;
            }
            else {
                stack_layout.BackgroundColor = Color.Yellow;
                flag = true;
            }
        }
    

    Xamarin forums are migrating to a new home on Microsoft Q&A! We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A! For more information, please refer to this sticky post.

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Friday, December 4, 2020 8:59 AM

All replies

  • User371688 posted

    You can define a globle variabe as follows:

         bool flag = true;
    

    And when we click the button, we can change the background color acccording to the value of this variable.

        private void Button_Clicked(object sender, EventArgs e)
        {
    
            if (flag)
            {
                stack_layout.BackgroundColor = Color.Green;
                flag = false;
            }
            else {
                stack_layout.BackgroundColor = Color.Yellow;
                flag = true;
            }
        }
    

    Xamarin forums are migrating to a new home on Microsoft Q&A! We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A! For more information, please refer to this sticky post.

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Friday, December 4, 2020 8:59 AM
  • User398284 posted

    Thanks very much

    Tuesday, December 8, 2020 4:52 AM