Set StateListDrawable for a view at runtime.

I am trying to setup a StateListDrawable with two colors -- a selected color and a default color. This is what I am doing. It's not working -- all I see is a transparent background.. What am I missing?

private void SetStateListDrawable(Android.Graphics.Color bg, Android.Graphics.Color selectedBG) {
  StateListDrawable listBG = new StateListDrawable ();
  ColorDrawable normal = new ColorDrawable (bg);
  ColorDrawable selected = new ColorDrawable (selectedBG);
  listBG.AddState (new int[]{Android.Resource.Attribute.StateSelected}, selected);
  listBG.AddState (new int[]{Android.Resource.Attribute.StateEmpty}, normal);
  this.SetBackgroundDrawable (listBG);
}

(The StateEmpty part was a guess; I don't know what I am supposed to use for the default state and couldn't find any documentation.)

Posts

  • I now have it showing the "unselected" one all the time with the following. I am unclear why the selected one is not working.

    private void SetStateListDrawable(Android.Graphics.Color bg, Android.Graphics.Color selectedBG) {
      StateListDrawable listBG = new StateListDrawable ();
      ColorDrawable normal = new ColorDrawable (bg);
      ColorDrawable selected = new ColorDrawable (selectedBG);
      listBG.AddState (new int[]{Android.Resource.Attribute.StateEnabled}, normal);
      listBG.AddState (new int[]{Android.Resource.Attribute.StateSelected}, selected);
      this.SetBackgroundDrawable (listBG);
    }
    
Sign In or Register to comment.