RadioGroup和RadioButton的简单使用

2020-01-18  本文已影响0人  伪装的狼

布局文件添加:

<RadioGroup
android:id="@+id/radio"
android:layout_width="match_parent"
android:layout_height="match_parent" >

    <RadioButton
        android:id="@+id/xiaoming"
        android:text="小明"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <RadioButton
        android:id="@+id/daming"
        android:text="大明"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RadioGroup>

MainActivity代码:

    //获取RadioGroup的Id
    RadioGroup radioGroup = findViewById(R.id.radio);
    //指定选中显示的选项
    radioGroup.check(R.id.daming);
    //监听RadioGroup
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {

           switch (checkedId){
                case R.id.xiaoming:
                    Toast.makeText(MainActivity.this,"You Click xiaoming!",Toast.LENGTH_SHORT).show();
                    break;
                case R.id.daming:
                    Toast.makeText(MainActivity.this,"You Click daming!",Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
            
        }
    });
image.png
上一篇 下一篇

猜你喜欢

热点阅读