RadioButton:
单选按钮:是TextView的子类,如果想要有互斥效果必须配合RadioGroup使用,否则多个按钮都可被选中。
<RadioGroup //RadioGroup是LinearLayout的子类,所以可以设置水平或者垂直显示,即其他属性 android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rg" android:orientation="horizontal"> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/nan" android:text="男" /> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/nv" android:text="女" /> </RadioGroup>
属性:android:checked=“” 参数作用设置默认选择状态 true表示选中,false表示不选中。
如果不设置该属性,则默认为false不选中。
<RadioGroup android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rg" android:orientation="horizontal"> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/nan" android:checked="true" //在这里设置默认选中 android:text="男" /> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/nv"android:checked="true"//同一单选组中只能有一个默认选中,否则多个被选中很难更改 android:text="女" /> </RadioGroup>
在代码中可以通过实例化对象RadioButton调用setChecked方法达到同样的效果。
效果与注意事项与上相同
RadioGroup:
单选按钮组:是LinearLayout的子类,可横向或者纵向排列。如果RadioButton想要有互斥效果则必须配合RadioButton使用,RadioGroup也可以用来组合多选框,以便多选框布局,用法与单选按钮一样
<RadioGroup android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/rg" android:orientation="horizontal"> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/cb1" android:text="A" /> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/cb2" android:text="B" /> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/cb3" android:text="C" /> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/cb4" android:text="D" /> </RadioGroup>
单选按钮组的监听器 :OnCheckedChangeListener();
CheckBox:
选择框:可以选中,再次点击则取消选中状态。(可嵌套其他监听器)
选择框监听器:setOnCheckedChangeListener();
CheckBox cb2=findViewById(R.id.cb2); cb2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ Toast.makeText(MainActivity.this,"你选择了B",Toast.LENGTH_SHORT).show(); } } });
checkBox.isChecked(),的返回值为boolean类型,来判断选择框是否被选中,当返回值是true的时候表示被选中,否则没有被选中。