setItemChecked not working on Gingerbread

前端 未结 1 1323
孤独总比滥情好
孤独总比滥情好 2021-01-17 04:16

I am using the following selector to change the appearance of text in a listView item:



        
1条回答
  •  粉色の甜心
    2021-01-17 04:33

    After a little searching, it seems to me the reason that the state_checked isn't expressed pre-Honeycomb is the fact that the setActive method on View is not available before API level 11. This means that the checked state is not propagated to the child views of my layout.

    THE KEY:

    1. Swap the TextView for a CheckedTextView
    2. Propagate the checked state from the parent view to the children

    1) Was a simple switch in the XML, and for 2) I modified the code in the answer linked to by Voicu to give the following:

    public class CheckableRelativeLayout extends RelativeLayout implements Checkable
    {
        private boolean checked = false;
    
        public CheckableRelativeLayout(Context context) {
            super(context, null);
        }
    
        public CheckableRelativeLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        private static final int[] CheckedStateSet = {
                R.attr.state_checked
        };
    
        @Override
        protected void dispatchSetPressed(boolean pressed)
        {
            super.dispatchSetPressed(pressed);
            setChecked(pressed);
        }
    
        @Override
        public void setChecked(boolean checked) {
            this.checked = checked;
            for (int index = 0; index < getChildCount(); index++)
            {
                View view = getChildAt(index);
                if (view.getClass().toString().equals(CheckedTextView.class.toString()))
                {
                    CheckedTextView checkable = (CheckedTextView)view;
                    checkable.setChecked(checked);
                    checkable.refreshDrawableState();
                }
            }
            refreshDrawableState();
        }
    
        public boolean isChecked() {
            return checked;
        }
    
        public void toggle() {
            checked = !checked;
            refreshDrawableState();
        }
    
        @Override
        protected int[] onCreateDrawableState(int extraSpace) {
            final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
            if (isChecked()) {
                mergeDrawableStates(drawableState, CheckedStateSet);
            }
            return drawableState;
        }
    
        @Override
        public boolean performClick() {
            return super.performClick();
        }
    }
    

    0 讨论(0)
提交回复
热议问题