动态地将RadioButton添加到RadioGroup会中断互斥选择

时间:2018-10-03 12:30:12

标签: android android-radiobutton android-radiogroup

这是在自定义视图类内部,该类扩展了RelativeLayout,而不是在Activity或Fragment内部。 我的RadioGroup存在于我的xml中,我正在尝试向其中动态添加RadioButtons。我唯一看到互斥不起作用的地方是,如果您不添加ID,但我在这里。当我点击一个单选按钮时,一次选择了多个按钮,会发生什么情况。我在这里想念什么?

 for(String buttonName : mButtonNames){

         RadioButton radioButton = new RadioButton(getContext());

         radioButton.setId(ViewCompat.generateViewId() );
         radioButton.setText(buttonName);

         LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
         layoutParams.weight = 1;
         radioButton.setLayoutParams(layoutParams);

         radioButton.setBackground(mRadioBckgrdDrawable);
         radioButton.setButtonDrawable(null);
         radioButton.setGravity(Gravity.CENTER);

         radioButton.setTextSize(mTextSize);
         radioButton.setTextColor(mTextColor);

         mRadioGroup.addView(radioButton);
 }

背景可绘制:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected-->
    <item android:drawable="@drawable/two_stage_toggle_button_on"
        android:state_checked="true" />
    <!-- When not selected-->
    <item android:drawable="@drawable/two_stage_toggle_button_off"
        android:state_checked="false"/>
</selector>

0 个答案:

没有答案