6

我想减小 Switch 的宽度。How to change the size of a Switch Widget and How to change Width of Android's Switch track?中的当前解决方案?没有解决我的问题。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;

我正在考虑使用负填充,但是有这条线paddingLeft = Math.max(paddingLeft, inset.left);。我不确定如何将 设置为inset具有负值的拇指可绘制对象(我不知道是什么insetOpticalBounds也许这应该是另一个 stackoverflow 问题)。

任何人都知道如何缩小 SwitchCompat 的宽度?

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

4

1 回答 1

2

我可以解决挑战的当前方法是在调用函数后立即使用反射强制设置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();
        }
    }
}

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

如果那里没有解决方案,那么这将是目前帮助面临同样挑战的其他人的最佳选择。

于 2016-11-04T15:17:38.607 回答