0

I'm trying to programmatically define some custom drawables for Switch, using jelly bean introduced setXXXDrawable() methods. However, things are not working out for me.

My current code:

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    ((Switch) view).setShowText(true);

  //Background
  StateListDrawable back = new StateListDrawable();
  GradientDrawable backn = new GradientDrawable();
  backn.setColor(TX.res.getColor(R.color.textSecondary));
  backn.setCornerRadius(8 * TX.res.getDisplayMetrics().scaledDensity);
  GradientDrawable backd = new GradientDrawable();
  backn.setColor(TX.res.getColor(R.color.textDisabled));
  backn.setCornerRadius(8 * TX.res.getDisplayMetrics().scaledDensity);
  back.addState(new int[]{-android.R.attr.state_enabled}, backd);
  back.addState(StateSet.WILD_CARD, backn);

  ((Switch) view).setTrackDrawable(back);

  GradientDrawable thumbn = new GradientDrawable();
  thumbn.setColor(TX.res.getColor(R.color.colorAccent));
  thumbn.setCornerRadius(8 * TX.res.getDisplayMetrics().scaledDensity);
  //((Switch) view).setThumbDrawable(thumbn);

Both JellyBean and Lollipop work as intended if I only set thumb drawable.

If I only set the track drawable, then lollipop displays it correctly. If I also set thumb drawable, lollipop draws neither, it just draws the text.

Jelly bean on the other hand just displays a few dots immediately when I try to set track drawable. The dots clearly belong to thumb (even if I set only track drawable) because they move when the switch is pressed.

How can I declare my drawables such that this would work in my favour?

velis
  • 8,747
  • 4
  • 44
  • 64

1 Answers1

0

The height of the switch is determined exclusively by the track drawable, the default size of a GradientDrawable is presumably 0 or 1, I found that setting the size fixes the problem.

[...]
backn.setSize(1,50);
[...]
backd.setSize(1,50);

note that the width of the switch and the track is based exclusively on twice the width of the thumb widget which is the size of the largest width for the on or off state. That's why it doesn't matter if the width of the track is one pixel.