I dealt with a similar issue today and I found out that starting from Jelly Bean you can use setSwitchMinWidth(width);
to set the minimum width of the complete switch. I also figured however that if your texts are too big, the widget is just cut off on the left part. Changing the default text padding on the thumb might come in handy here, with setThumbTextPadding(num);
you can modify that.
The only problem - and this is a blocker actually - I've stumbled so far is that one should of course expand the switch according to the size of the parent container. For that I wrapped the switch in a custom linear layout (which also provides a fallback for API <= 15) and tried this:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (android.os.Build.VERSION.SDK_INT >= 16) {
adaptSwitchWidth(w);
}
}
@TargetApi(16)
private void adaptSwitchWidth(int containerWidth) {
Switch sw = (Switch) compoundButton;
sw.setSwitchMinWidth(containerWidth);
}
Unfortunately - for whatever stupid reason - the switch widget doesn't react on that. I tried to do that in an OnLayoutChangeListener
without having success either. Ideally, the current size of the switch should also be known at that state and I wanted to "distribute" the free space to the padding like this:
int textPadding = Math.max(0, (sw.getWidth() - containerWidth) / 4);
sw.setThumbTextPadding(textPadding);
but sw.getWidth()
still returns 0 in onSizeChanged()
, probably because it is still not layed out properly. Yeah, we're almost there... if you stumble across something, let me know :)