单选按钮RadioButton

来源:互联网 发布:全金属开放式网络桥架 编辑:程序博客网 时间:2024/05/16 12:59

单选按钮RadioButton

<RadioButton        android:id="@+id/radioButton_main"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="单选按钮" />    <RadioGroup        android:id="@+id/radioGroup_main"        android:layout_width="wrap_content"        android:layout_height="wrap_content" >        <RadioButton            android:id="@+id/radio_man"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:checked="true"            android:text="男" />        <RadioButton            android:id="@+id/radio_woman"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="女" />    </RadioGroup>
@Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // 关联布局文件        setContentView(R.layout.activity_main);        mRadioButton = (RadioButton) findViewById(R.id.radioButton_main);        mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup_main);        // 设置单选按钮的监听事件        mRadioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {            @Override            public void onCheckedChanged(CompoundButton buttonView,                    boolean isChecked) {                if (isChecked) {                    Log.e("mRadioButton", "被选中了");                }            }        });        // 设置单选按钮组的监听事件        mRadioGroup.setOnCheckedChangeListener(                new RadioGroup.OnCheckedChangeListener() {                    @Override                    public void onCheckedChanged(RadioGroup group,                            int checkedId) {                        switch (checkedId) {                        case R.id.radio_man:                            Log.e("mRadioGroup", "选中男生");                            break;                        case R.id.radio_woman:                            Log.e("mRadioGroup", "选中女生");                            break;                        }                        // 改变第一个单选按钮的选中状态                        mRadioButton.setChecked(false);                    }                });        int id = mRadioGroup.getCheckedRadioButtonId();        Log.e("当前被选中的id为", "id = "+id);        int childCount = mRadioGroup.getChildCount();        Log.e("选项总数", childCount+"");        String totalName = "";        for (int i = 0; i < childCount; i++) {            RadioButton rb = (RadioButton) mRadioGroup.getChildAt(i);            totalName += rb.getText().toString();        }        Log.e("选项有", totalName);    }

“`
这里写图片描述

0 0