Forum Xamarin.Android

Click background color.

BKustraBKustra PLMember

Hi, I have a problem.
How can I set Background Color for Button, which was clicked? I know selectors, but I need to do in code behind.


  • PeterDavisPeterDavis USMember ✭✭✭

    This works:

    Button btn = FindViewById<Button >(Resource.Id.btnMyButton);
  • BKustraBKustra PLMember

    Yea, I know. But I need to set background color when button is clicked.

  • CheesebaronCheesebaron DKInsider, University mod

    You need a StateList Drawable for that.

  • PeterDavisPeterDavis USMember ✭✭✭

    Oh, then what Cheesebaron said. I thought you meant after the click, not during the click.

  • HarshadcseHarshadcse USMember ✭✭✭

    @BKustra‌ try to this way

    first create buttonselector.xml file.

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="">
        <item android:drawable="@drawable/DarkGray"
              android:state_pressed="true" />
        <item android:drawable="@drawable/DarkGray"
              android:state_focused="true" />
        <item android:drawable="@drawable/LightGray" />

    then set button background properties (android:background="@drawable/buttonselector" ).
    working ...



  • BKustraBKustra PLMember

    I know it working, but I have lot of buttons with different background color, not one bg color or 5 maybe. So my background color in selector should be non-static

  • CheesebaronCheesebaron DKInsider, University mod

    Well then either load it into an instance you can modify or create your own instance of it:

    var drawable = new StateListDrawable ();
    drawable.AddState (new[] { Android.Resource.Attribute.StateFocused },
        new ColorDrawable () { Color = Color.Brown });
    drawable.AddState (new[] { Android.Resource.Attribute.StatePressed },
        new ColorDrawable () { Color = Color.Yellow });

    If you had searched for a couple of seconds you would also have found:

  • BKustraBKustra PLMember


    I saw this topic.
    But it doens't work in my project.

    I have this code:
    var drawable = new StateListDrawable (); drawable.AddState (new[] { Android.Resource.Attribute.StatePressed }, Resources.GetDrawable(Resource.Color.col3)); button3a.SetBackgroundDrawable (drawable);

    and my button is white, and when is clicked, he is a blue (col3).
    What I'm doing wrong?

  • CheesebaronCheesebaron DKInsider, University mod

    And what did you expect it to be? You most likely need to set the color or drawable for each state.

Sign In or Register to comment.