3状态开关按钮?

时间:2017-05-31 08:24:54

标签: android button android-button

要求是实现这样的3路开关按钮..

switch

yes

[插入无状态开关]

我检查过的几乎每个地方都只有2个状态的Switch按钮,我找到的唯一3个选项是切换。

有人使用/知道如何解决这种情况吗?

1 个答案:

答案 0 :(得分:1)

  • 您必须定义一个扩展Checkbox的类

  • 定义检查状态的变量

  • 重写onClick或onCheck方法,在3个状态之间更改该变量,而不是切换isChecked变量。



static private final int CHECKED = 1;
private int state;

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

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

public CheckBoxTriStates(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init()
{
    state = UNKNOW;
    updateBtn();

    setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        // checkbox status is changed from uncheck to checked.
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            switch (state)
            {
                case UNKNOW:
                    state = UNCHECKED;
                    break;
                case UNCHECKED:
                    state = CHECKED;
                    break;
                case CHECKED:
                    state = UNKNOW;
                    break;
            }
            updateBtn();
        }
    });

}

private void updateBtn()
{
    int btnDrawable = R.drawable.ic_checkbox_indeterminate_black;
    switch (state)
    {
        case UNKNOW:
            btnDrawable = R.drawable.ic_checkbox_indeterminate_black;
            break;
        case UNCHECKED:
            btnDrawable = R.drawable.ic_checkbox_unchecked_black;
            break;
        case CHECKED:
            btnDrawable = R.drawable.ic_checkbox_checked_black;
            break;
    }
    setButtonDrawable(btnDrawable);

}
public int getState()
{
    return state;
}

public void setState(int state)
{
    this.state = state;
    updateBtn();
}

}