gpt4 book ai didi

android - 如何缩小 SwitchCompat 宽度?

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:46 27 4
gpt4 key购买 nike

我想减少 Switch 的宽度。当前解决方案在How to change the size of a Switch WidgetHow to change Width of Android's Switch track?没有解决我的问题。 android:switchMinWidth 刚刚定义了最小宽度,但我希望它小于 2 x thumbWidth 大小。

我深入研究了 SwitchCompat class' onMeasure() 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 设置为具有负值的拇指可绘制对象(我不知道什么是 insetOpticalBounds . 也许这应该是另一个 stackoverflow 问题)。

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

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

最佳答案

目前我可以解决这个挑战的方法是使用反射在调用 onMeasure(...) 函数后立即强制设置 mSwitchWidth 变量。

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();
}
}
}

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

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

关于android - 如何缩小 SwitchCompat 宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40392990/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com