如何创建从 ToggleButton 扩展但具有 CircleButton 样式的自定义视图?

How can I create a custom view extending from ToggleButton but with the CircleButton style?

我想创建一个普通的 ToggleButton,但具有此 library

的样式和效果

我该怎么做?也许创建一个从 ToggleButton 或 CircleButton 扩展的自定义视图?是否有用于样式化的 ToggleButton 的任何库?

您可以使用如下内容扩展库中给出的 CircleButton class:

public class CustomCircleButton extends CircleButton {
    boolean state = false;

    private int checked = R.drawable.ic_action_check;
    private int unchecked = R.drawable.ic_action_clear;

    public CustomCircleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomCircleButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

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

    private void init() {
        //Set the default on click to do nothing but toggle
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //Empty
            }
        });
        setImageResource(unchecked); //Set default drawable
    }
    private void toggle() {
        if(state) {
            state = false;
            //Set drawable for true
            setImageResource(checked);
        } else {
            state = true;
            //Set drawable for false
            setImageResource(unchecked);
        }
    }

    @Override
    public void setOnClickListener(final OnClickListener l) {
        super.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                toggle();
                l.onClick(v);
            }
        });
    }
    //Helper methods
    public boolean isChecked() {
        return state;
    }

    public void setCheckedIcon(int id) {
        this.checked = id;
    }
    public void setUncheckedIcon(int id) {
        this.unchecked = id;
    }
}

然后你所要做的就是定义这两个状态并将其添加到视图中。

<com.yourpackage.CustomCircleButton
            android:layout_width="64dip"
            android:layout_height="64dip"
            app:cb_color="#99CC00"
            app:cb_pressedRingWidth="8dip" />