首页 > 解决方案 > 使用 rightDrawable 在错误位置上的 CheckBox 触摸动画

问题描述

我正在使用使用 rightDrawable 属性的 rtl 支持的自定义复选框。

public class SRCheckBox extends AppCompatCheckBox {

    public SRCheckBox(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        if (isRTL()) {
            this.setButtonDrawable(null);
            int[] attrs = {android.R.attr.listChoiceIndicatorMultiple};
            TypedArray ta = context.getTheme().obtainStyledAttributes(attrs);
            Drawable rightDrawable = ta.getDrawable(0);
            this.setCompoundDrawablesWithIntrinsicBounds(null, null, rightDrawable, null);
        }
    }

}

但这是我面临的问题:请看这个 gif

gif

如您所见,触摸动画影响的是左侧(文本),而不是复选框本身的动画。

我也试过XML

<CheckBox
    android:id="@+id/fastDecodeCB"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@null" // this is causing the problem
    android:drawableRight="?android:attr/listChoiceIndicatorMultiple" />

但它看起来一样。有什么建议么?

标签: androidandroid-layoutandroid-custom-viewandroid-checkbox

解决方案


您正在将复选框按钮设置为 null,从而有效地删除它并设置正确的可绘制对象。正确的drawable响应点击,但复选框并不真正知道drawable是按钮(你告诉它没有按钮),所以它只是你看到的。

在您的自定义视图中尝试以下 init 方法。

private void init(Context context) {
    if (isRTL()) {
        // This will flip the text and the button drawable. This could also be set in XML.
        setLayoutDirection(LAYOUT_DIRECTION_RTL);
        int[] attrs = {android.R.attr.listChoiceIndicatorMultiple};
        TypedArray ta = context.getTheme().obtainStyledAttributes(attrs);
        Drawable rightDrawable = ta.getDrawable(0);
        this.setButtonDrawable(rightDrawable);
        ta.recycle(); // Remember to do this.
    }
}

推荐阅读