踩坑之路:RadioGroup+RadioButton

背景

  相信大家对RadioGroup+RadioButton组合的单选框布局再熟悉不过了,我自己也是这么觉得的。于是今天非常自信的写了如下一段代码:

        <RadioGroup
            android:id="@+id/rg_sex_select"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="15dp"
            app:layout_constraintStart_toStartOf="@+id/et_input_name"
            app:layout_constraintEnd_toEndOf="@+id/et_input_name"
            app:layout_constraintTop_toBottomOf="@+id/et_input_name">
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/dimen_sp15"
                android:textColor="#DFB774"
                android:button="@null"
                android:drawableStart="@drawable/selector_sex_select"
                android:drawablePadding="10dp"
                android:checked="true"
                android:layout_marginStart="15dp"
                android:text="@string/login_sex_male"/>
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/dimen_sp15"
                android:textColor="#DFB774"
                android:layout_marginStart="45dp"
                android:checked="false"
                android:button="@null"
                android:drawableStart="@drawable/selector_sex_select"
                android:drawablePadding="10dp"
                android:text="@string/login_sex_female"/>
        </RadioGroup>

然后直接运行,跑起来以后发现单选效果怎么都出不来,我可以同时选中这两个Button。
我一下子就懵逼了,怎么回事?我用的这么熟练的东西,怎么现在没法实现了。
然后我找了以前的代码比较了一下,发现现在写的这段代码RadioButton没有加上ID。难道就因为没有加ID导致的,于是给RadioButton加上了ID,跑了一下,发现还真的是这样,心里说了句FxxK。


为了搞清楚原因,于是乎我就开始了一次代码的深入研究。
1、首先点击事件是RadioButton检测到的,所以我先去看了下RadioButton的点击事件:

public class RadioButton extends CompoundButton {
    
    public RadioButton(Context context) {
        this(context, null);
    }
    
    public RadioButton(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.radioButtonStyle);
    }

    public RadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public RadioButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    /**
     * {@inheritDoc}
     * <p>
     * If the radio button is already checked, this method will not toggle the radio button.
     */
    @Override
    public void toggle() {
        // we override to prevent toggle when the radio is already
        // checked (as opposed to check boxes widgets)
        if (!isChecked()) {
            super.toggle();
        }
    }

    @Override
    public CharSequence getAccessibilityClassName() {
        return RadioButton.class.getName();
    }
}

并没有发现什么点击事件处理,于是去找他的父类CompoundButton:

    @Override
    public boolean performClick() {
        toggle();

        final boolean handled = super.performClick();
        if (!handled) {
            // View only makes a sound effect if the onClickListener was
            // called, so we'll need to make one here instead.
            playSoundEffect(SoundEffectConstants.CLICK);
        }

        return handled;
    }

在点击时会触发performClick事件,至于为什么会触发这里暂时不做分析。出发performClick事件以后,会执行toggle方法,那再来看下toggle里面的处理

    @Override
    public void toggle() {
        setChecked(!mChecked);
    }

    /**
     * <p>Changes the checked state of this button.</p>
     *
     * @param checked true to check the button, false to uncheck it
     */
    @Override
    public void setChecked(boolean checked) {
        if (mChecked != checked) {
            mCheckedFromResource = false;
            mChecked = checked;
            refreshDrawableState();
            notifyViewAccessibilityStateChangedIfNeeded(
                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);

            // Avoid infinite recursions if setChecked() is called from a listener
            if (mBroadcasting) {
                return;
            }

            mBroadcasting = true;
            if (mOnCheckedChangeListener != null) {
                mOnCheckedChangeListener.onCheckedChanged(this, mChecked);
            }
            if (mOnCheckedChangeWidgetListener != null) {
                mOnCheckedChangeWidgetListener.onCheckedChanged(this, mChecked);
            }
            final AutofillManager afm = mContext.getSystemService(AutofillManager.class);
            if (afm != null) {
                afm.notifyValueChanged(this);
            }

            mBroadcasting = false;
        }
    }

OnCheckedChangeListener监听器在RadioGroup如下代码里面进行注册

        /**
         * {@inheritDoc}
         */
        @Override
        public void onChildViewAdded(View parent, View child) {
            if (parent == RadioGroup.this && child instanceof RadioButton) {
                int id = child.getId();
                // generates an id if it's missing
                if (id == View.NO_ID) {
                    id = View.generateViewId();
                    child.setId(id);
                }
                ((RadioButton) child).setOnCheckedChangeWidgetListener(
                        mChildOnCheckedChangeListener);
            }

            if (mOnHierarchyChangeListener != null) {
                mOnHierarchyChangeListener.onChildViewAdded(parent, child);
            }
        }

mChildOnCheckedChangeListener这个对象呢是实现了CompoundButton.OnCheckedChangeListener接口,重写了onCheckedChanged方法,接下来要执行的方法就是这里面的onCheckChanged方法:

    private class CheckedStateTracker implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            ...代码省略....
            //当前checkedID不为-1的时候,将当前选中的按钮置为未选中状态
            if (mCheckedId != -1) {
                setCheckedStateForView(mCheckedId, false);
            }
           ...代码省略...

            int id = buttonView.getId();
            setCheckedId(id);
        }
    }

最主要的就是这几行了,之所以能实现单选的原因是调用setCheckedStateForView将选中的RadioButton设置为未选中状态,然后先获取RadioButton的id,调用setCheckedId设置当前按下的RadioButton设置为选中状态。显而易见我之前所说的单选框效果实现原因就应该是mCheckedId == -1了。
那么为什么mChecked会等于-1呢,什么时候才会有值呢?
CTRL+F整个类搜索了一下「mChecked =」发现只有两处有赋值情况

    /**
     * {@inheritDoc}
     */
    public RadioGroup(Context context, AttributeSet attrs) {
        super(context, attrs);

        ...代码省略...

        int value = attributes.getResourceId(R.styleable.RadioGroup_checkedButton, View.NO_ID);
        if (value != View.NO_ID) {
            mCheckedId = value;
            mInitialCheckedId = value;
        }
        ...代码省略...
    }

此处是布局初始化,给他设置属性的时候赋值的。
这里我直接讨论第二处:

    private void setCheckedId(@IdRes int id) {
        boolean changed = id != mCheckedId;
        mCheckedId = id;

        if (mOnCheckedChangeListener != null) {
            mOnCheckedChangeListener.onCheckedChanged(this, mCheckedId);
        }
        if (changed) {
            final AutofillManager afm = mContext.getSystemService(AutofillManager.class);
            if (afm != null) {
                afm.notifyValueChanged(this);
            }
        }
    }

这里面的ID就是RadioButton的ID。所以如果没有设置ID的,单选框将会失效


  虽然这次碰到问题比较简单,但是也从侧面说明了源码的了解程度还是比较薄弱的。以后得多看源码,才能更好的解决问题。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容