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

时间:2015-08-13 19:29:01

标签: android togglebutton

我想创建一个普通的ToggleButton但是具有这个library的风格和效果

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

1 个答案:

答案 0 :(得分:0)

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

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" />