CheckBox使用rightDrawable在错误位置触摸动画

时间:2019-02-11 04:48:16

标签: android android-layout android-custom-view android-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" />

,但是看起来一样。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您正在将复选框按钮设置为null,以有效地将其删除并设置右侧可绘制对象。正确的可绘制对象会对单击做出响应,但是复选框并不真正知道该可绘制对象是按钮(您告诉它没有按钮),因此它只是执行您看到的操作。

在您的自定义视图中尝试以下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.
    }
}