1、什么是RadioButton和RadioGroup:
之前学到了CheckBox,知道了CheckBox是复选框,那么RadioButton应该就是CheckBox的死对头了—也就是单选按钮。但是RadioButton一般不单独使用,而是通过RadioGroup将RadioButton集合到一起,提供多选一机制。
举个栗子:你在选择性别时,要么男,要么女,只能选一个,它的实现就是将两个RadioButton放到同一个RadioGroup中。
2、RadioGroup的常用属性:
android:orientation=”vertical” ——-垂直排布
android:orientation=”horizontal” ——-水平排布
3、效果图
通过与CheckBox对比就可以看出这里呈现的是单选按钮。
4、代码实现:
(1)首先是添加布局:
//在一个RadioGroup中添加3个RadioButton
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical" > //垂直排布
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="篮球" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="羽毛球" />
<RadioButton
android:id="@+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="足球" />
</RadioGroup>
(2)回到MainActivity添加逻辑代码,完整代码如下:
public class MainActivity extends Activity implements OnCheckedChangeListener{ //实现的是OnCheckedChangeListener接口,在实现接口的时候需要注意导入的包,不要导错了
private RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rg=(RadioGroup) findViewById(R.id.radioGroup);
rg.setOnCheckedChangeListener(this);
}
/**
*第一个参数说明是哪一个RadioGroup
*第二个参数指的是当前RadioGroup中被选中的RadioButton的id
*/
public void onCheckedChanged(RadioGroup rg, int checkedId) {
// TODO Auto-generated method stub
switch(checkedId){
case R.id.radio1:
Toast.makeText(getApplicationContext(), "你选择了篮球", 1).show();
break;
case R.id.radio2:
Toast.makeText(getApplicationContext(), "你选择了羽毛球", 1).show();
break;
case R.id.radio3:
Toast.makeText(getApplicationContext(), "你选择了足球", 1).show();
break;
}
}
}