RadioButton和RadioGroup小案例

RadioButton和CheckBox的区别:

1、单个RadioButton在选中后,通过点击无法变为未选中;单个CheckBox在选中后,通过点击可以变为未选中

2、一组RadioButton,只能同时选中一;一组CheckBox,能同时选中多个

3、RadioButton在大部分UI框架中默认都以圆形表示;CheckBox在大部分UI框架中默认都以矩形表示

RadioButton和RadioGroup的关系:

1、RadioButton表示单个圆形单选框,而RadioGroup是可以容纳多个RadioButton的容器

2、每个RadioGroup中的RadioButton同时只能有一个被选中

3、不同的RadioGroup中的RadioButton互不相干,即如果组A中有一个选中了,组B中依然可以有一个被选中

4、通常,一个RadioGroup中至少有2个RadioButton

5、通常,一个RadioGroup中的RadioButton默认会有一个被选中,并建议您将它放在RadioGroup中的起始位置

MainActivity中的代码:

    TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        //根据ID找到该文本控件
        tv = (TextView)this.findViewById(R.id.tvSex);
        //根据ID找到RadioGroup实例
        RadioGroup group = (RadioGroup)this.findViewById(R.id.radioGroup);
        //绑定一个匿名监听器
        group.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                //获取变更后的选中项的ID
                int radioButtonId = arg0.getCheckedRadioButtonId();
                //根据ID获取RadioButton的实例
                RadioButton rb = (RadioButton)MyActiviy.this.findViewById(radioButtonId);
                //更新文本内容,以符合选中项
                tv.setText("您的性别是:" + rb.getText());
            }
        });
    }

xml布局文件中的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="请选择您的性别:"
        />

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="性别" >

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="男" >
        </RadioButton>

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="女" >
        </RadioButton>
    </RadioGroup>

    <TextView
        android:id="@+id/tvSex"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="您的性别是:男"
         />

</LinearLayout>

原文地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值