Custom Checkable View which responds to Selector

前端 未结 6 477
生来不讨喜
生来不讨喜 2021-01-30 23:11

I have a group of FrameLayout which I want to be checkable/selectable,

That is, after a click I would like the FrameLayout to display as

6条回答
  •  盖世英雄少女心
    2021-01-30 23:53

    Here's a complete working example for a CheckableButton. It also works on Android 4.2.

    public class CheckableButton extends Button implements Checkable {
    
        private static final int[] CheckedStateSet = { android.R.attr.state_checked };
    
        private boolean mChecked = false;
    
        public CheckableButton(Context context) {
            super(context);
        }
    
        public CheckableButton(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public CheckableButton(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        public boolean isChecked() {
            return mChecked;
        }
    
        @Override
        public void setChecked(boolean checked) {
            mChecked = checked;
            refreshDrawableState();
        }
    
        @Override
        public void toggle() {
            mChecked = !mChecked;
            refreshDrawableState();
        }
    
        @Override
        protected int[] onCreateDrawableState(int extraSpace) {
            final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
            if (isChecked()) {
                mergeDrawableStates(drawableState, CheckedStateSet);
            }
            return drawableState;
        }
    }
    

提交回复
热议问题