Creating a three states checkbox on android

前端 未结 3 444
独厮守ぢ
独厮守ぢ 2020-12-31 02:18

I\'m stuck in front of a big problem: I\'d like to make three state checkbox on android. It\'s a checkbox upon a ListView with checkboxes. It should allows user to switch be

3条回答
  •  旧巷少年郎
    2020-12-31 03:08

    Old topic, but I give my solution for who are interessed:

    public class CheckBoxTriStates extends CheckBox {
        static private final int UNKNOW = -1;
        static private final int UNCHECKED = 0;
        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) {
                        default:
                        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) {
                default:
                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();
        }
    }
    

    You can find the button resources Here. It work perfect.

提交回复
热议问题