学Android---RadioGroup和RadioButton

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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值