如何缩小 SwitchCompat 宽度?

Ely*_*lye 7 android switchcompat

我想减小 Switch 的宽度。当前的解决方案如何更改 Switch Widget 的大小如何更改 Android 的 Switch 轨道的宽度?没有解决我的问题。android:switchMinWidth刚刚定义了 minWidth,但我希望它小于2 x thumbWidthsize。

我深入研究了SwitchCompat班级的onMeasure()功能。宽度的定义方式如下。

    // 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;
Run Code Online (Sandbox Code Playgroud)

我正在考虑使用负填充,但后来出现了这一行paddingLeft = Math.max(paddingLeft, inset.left);。我不知道如何设置inset具有负值的拇指可绘制对象(我不知道是什么inset或是OpticalBounds什么。也许这应该是另一个 stackoverflow 问题)。

有人知道如何缩小 SwitchCompat 的宽度吗?

更新我已就此https://code.google.com/p/android/issues/detail?id=227184&thanks=227184&ts=1478485498 向谷歌提出请求

Ely*_*lye 3

目前我可以解决这一挑战的方法是使用反射在调用函数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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这并不理想。我希望其他人能够提供更好的答案,而不需要反射(或者复制整个类来修改类,或者仅仅因为宽度问题而重写自定义 Switch)。

如果没有解决方案,那么现在最好的方法是帮助面临同样挑战的其他人。