为了在右侧创建一个复选框,我查看了 Android 中的代码。但我对 android 在哪里测量复选框图标/可绘制对象的宽度感到困惑。
Checkbox 扩展了 CompoundButton 类并且只覆盖了 onPopulateAccessibilityEvent 方法。 CompoundButton 类的代码稍多(100 行),它扩展了 Button 类。按钮类有很少的额外代码并扩展了 TextView 类。 TextView 类的代码量最大(10,000 行)。
这里是源代码链接
TextView 网页语法高亮 http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.3_r1/android/widget/TextView.java?av=f
TextView 具有称为复合可绘制对象 的功能,您可以在其中将可绘制对象放置在文本的左侧、右侧、底部或顶部。所以我假设这是 CompoundButton 为左侧复合可绘制对象设置复选框可绘制对象的地方。但是在 CompoundButton 代码中我找不到这个。
但是,当我通过扩展 CompoundButton 创建自定义类并调用 getCompoundPaddingLeft() 时,它给出的宽度大约等于复选框的大小。但是,当您运行 getCompoundDrawables() 时,即使在 onDraw() 点,结果也是一个空数组。 在 textView 中,保存所有维度数据的变量都是私有(private)的,所以我不确定 CompoundButton 如何设置这些值。这是 TextView 中 getCompoundPaddingLeft() 的示例
public int getCompoundPaddingLeft() {
final Drawables dr = mDrawables;
if (dr == null || dr.mDrawableLeft == null) {
return mPaddingLeft;
} else {
return mPaddingLeft + dr.mDrawablePadding + dr.mDrawableSizeLeft;
}
}
这是 CompoundButton 中的代码,其中设置了可绘制的复选框,似乎无论如何都不会传递给 TextView 现在左侧有一个可绘制的图像。
public void setButtonDrawable(Drawable d) {
if (d != null) {
if (mButtonDrawable != null) {
mButtonDrawable.setCallback(null);
unscheduleDrawable(mButtonDrawable);
}
d.setCallback(this);
d.setState(getDrawableState());
d.setVisible(getVisibility() == VISIBLE, false);
mButtonDrawable = d;
mButtonDrawable.setState(null);
setMinHeight(mButtonDrawable.getIntrinsicHeight());
}
refreshDrawableState();
}
所以我的问题是CompoundButton 是如何设置左侧复合可绘制对象的宽度的?请注意,我对将复选框放在右侧的黑客攻击不感兴趣,因为我已经有了一个。
经进一步检查
我通过扩展 textview 类创建了一个自定义 textview 类,并让我的自定义 compoundButton 类对其进行了扩展,以尝试通过重写某些方法来确定创建复选框间距的位置。
为复选框创建空间的不是 compoundLeft,而是 paddingLeft。当我覆盖 setPadding() 方法时,paddingLeft 被发送给它。这就像在复选框上放置没有填充的背景一样有意义,不会绘制复选框。
正在从 textView 构造函数代码中的默认样式中读取填充
a = theme.obtainStyledAttributes( 属性, com.android.internal.R.styleable.TextView, defStyle, 0);
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case com.android.internal.R.styleable.TextView_editable:
editable = a.getBoolean(attr, editable);
break;
.............
由于我们无法访问正在使用的 com.android.internal.R.styleable,所以我不知道如何进一步检查。
最佳答案
onDraw()
CompoundButton
的方法似乎绘制了 mButtonDrawable
darwable 在 Canvas
上。代码显示它被绘制在左侧调整重力高度,drawable 的固有宽度按原样使用:
buttonDrawable.setBounds(0, y, buttonDrawable.getIntrinsicWidth(), y + height);
buttonDrawable.draw(canvas);
关于android - CompoundButton Checkbox 在哪里/如何测量可绘制复选框的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14314233/