我想缩小开关的宽度。How to change the size of a Switch Widget和How to change Width of Android's Switch track?中的当前解决方案不是解决我的问题。android:switchMinWidth刚刚定义了minWidth,但我希望它小于2 x thumbWidth大小。
我钻研 function。宽度的定义方式如下所示。
// Adjust left and right padding to ensure there's enough room for the
// thumb's padding (when present).
int paddingLeft = padding.left;
int paddingRight = padding.right;
if (mThumbDrawable != null) {
final Rect inset = DrawableUtils.getOpticalBounds(mThumbDrawable);
paddingLeft = Math.max(paddingLeft, inset.left);
paddingRight = Math.max(paddingRight, inset.right);
}
final int switchWidth = Math.max(mSwitchMinWidth,
2 * mThumbWidth + paddingLeft + paddingRight);
final int switchHeight = Math.max(trackHeight, thumbHeight);
mSwitchWidth = switchWidth;
mSwitchHeight = switchHeight;我正在考虑使用负填充,但还有这一行paddingLeft = Math.max(paddingLeft, inset.left);。我不知道如何将inset设置为具有负值的拇指绘图(我不知道inset或OpticalBounds是什么)。也许这应该是另一个堆叠溢出问题)。
有人知道我怎么能缩小SwitchCompat的宽度吗?
更新我在这个https://code.google.com/p/android/issues/detail?id=227184&thanks=227184&ts=1478485498上向谷歌提交了一个请求
发布于 2016-11-04 15:17:38
当前我可以解决的方法是在调用mSwitchWidth函数之后使用反射强制设置onMeasure(...)变量。
public class SwitchCustomWidth extends SwitchCompat {
//... the needing constructors goes here...
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
try {
Field switchWidth = SwitchCompat.class.getDeclaredField("mSwitchWidth");
switchWidth.setAccessible(true);
// Using 120 below as example width to set
// We could use attr to pass in the desire width
switchWidth.setInt(this, 120);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}这并不理想。我希望其他人提供一个更好的答案,而不需要反射(或者复制整个类来修改类,或者仅仅因为宽度问题而重写自定义开关)。
如果没有解决办法,那么现在最好的办法就是帮助面临同样挑战的其他人。
https://stackoverflow.com/questions/40392990
复制相似问题