分享

android控件 RadioButton

 风雪夜归人_95 2014-03-20
RadioGroup和RadioButton一般是一起使用的。一般一个RadioGroup中间包含两个或以上的RadioButton。我之所以把这个控件单独拿出来讨论是因为它的初始化和一般的控件有一点区别。
1)初始化一个RadioGroup
group1=(RadioGroup) findViewById(R.id.radioGroup1);
2)添加group1的监听事件:
group1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
   @Override
   public void onCheckedChanged(RadioGroup group, int checkedId) {
    int radiobtId = group.getCheckedRadioButtonId();
    RadioButton rb=(RadioButton)findViewById(radiobtId);
    Log.i("msg", "radiobtId="+radiobtId);
    gender = String.valueOf(rb.getText());
   }  
  });
你会发现在监听函数中,我们根据当前选择的groupbutton的ID来初始化RadioButton,并得到它的值。
 
布局文件如下:
<RadioGroup
            android:id="@+id/radioGroup1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
            <RadioButton
                android:id="@+id/radiomale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="男" />
            <RadioButton
                android:id="@+id/radiofemale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="女" />
        </RadioGroup>

RadioButton和RadioGroup的关系:

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

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

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

4、大部分场合下,一个RadioGroup中至少有2个RadioButton

5、大部分场合下,一个RadioGroup中的RadioButton默认会有一个被选中,并建议您将它放在RadioGroup中的起始位置

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多