Android控件: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中的起始位置

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/radioGrop"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">
    <RadioButton
        android:id="@+id/r1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="男"/>
    <RadioButton
        android:id="@+id/r2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="女"/>
  </RadioGroup>
  <TextView
      android:id="@+id/tv"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="您的性别是:男"/>


</LinearLayout>

活动代码:

public class MainActivity extends AppCompatActivity {

    private RadioGroup mRadioGroup;
    private TextView mTv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTv = (TextView) findViewById(R.id.tv);
        mRadioGroup = (RadioGroup) findViewById(R.id.radioGrop);
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                //获取选中的id
                int radioButtonId = radioGroup.getCheckedRadioButtonId();
                //根据id获取RadioButton的实例
                RadioButton rb = (RadioButton)findViewById(radioButtonId);
                //更新文本内容
                mTv.setText("您的性别是:" +rb.getText());
            }
        });
    }
}

效果如下:

posted on 2017-03-15 10:42  懂你在爱我  阅读(279)  评论(0)    收藏  举报

导航