具有可检查实现的FloatingActionButton

时间:2017-06-01 14:49:22

标签: android floating-action-button

我使用ActivityAppBarFloatingActionButton创建了RecyclerView。我实现了自己的FAB,因为我希望它可以检查。这是我的代码:

public class CheckableFloatingActionButton extends FloatingActionButton implements Checkable {

    private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};

    private boolean checked = false;
    private boolean broadcasting;

    private OnCheckedChangeListener onCheckedChangeListener;

    public interface OnCheckedChangeListener {

        void onCheckedChanged(CheckableFloatingActionButton fab, boolean isChecked);
    }

    public CheckableFloatingActionButton(Context context) {
        this(context, null);
    }

    public CheckableFloatingActionButton(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CheckableFloatingActionButton);
        setChecked(a.getBoolean(R.styleable.CheckableFloatingActionButton_checked, false));
        a.recycle();

    }

    @Override
    public void setChecked(boolean checked) {
        if (this.checked != checked) {
            this.checked = checked;
            refreshDrawableState();
            if (broadcasting) {
                return;
            }

            broadcasting = true;
            if (onCheckedChangeListener != null) {
                onCheckedChangeListener.onCheckedChanged(this, this.checked);
            }

            broadcasting = false;
        }
    }

    public void toggle(boolean animate) {
        if (animate) {
            setChecked(checked);
            return;
        }
        checked = !checked;
        jumpDrawablesToCurrentState();

    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
        onCheckedChangeListener = listener;
    }

    @Override
    public boolean performClick() {
        toggle();
        return super.performClick();
    }

    @Override
    public boolean isChecked() {
        return checked;
    }

    @Override
    public void toggle() {
        setChecked(!checked);
    }

    @Override
    public int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (isChecked()) {
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
        }
        return drawableState;
    }

}

它一直工作,直到我向上/向下滚动并隐藏/显示FAB。正如您所看到的,FAB动画可绘制而不是立即设置。这就是(我认为)错误发生的原因。有什么办法可以解决吗?

link

2 个答案:

答案 0 :(得分:1)

Android Studio中的FloatingActionButtonBasic示例包含Checkable FloatingActionButton的实现。使用CollapsingToolbarLayout向上/向下滚动时效果很好。但我认为使用https://developer.android.com/reference/android/widget/CompoundButton.html将是一个更优雅的解决方案。

答案 1 :(得分:0)

如果这是一个FloatingAcionsMenu,你可以使用一个监听器来扩展或不扩展,为什么不在扩展时使用监听器检查“checked”参数是否为true,以及是否填充了drawable。 / p>

NoSuchMethodError