- Radio buttons are normally used together in a RadioGroup
- 在RadioGroup中添加RadioButton(至少两个)
- 为对象添加监听器,实现OnCheckedChangeListener接口,(选择RadioGroup包下的那个)
XML 配置
<RadioGroup
android:id="@+id/rg_sex"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/rb_Male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男" />
<RadioButton
android:id="@+id/rb_FeMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女" />
</RadioGroup>
JAVA 使用
- public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener
private RadioGroup rg;
private RadioButton rg_Male, rg_Female;
rg = (RadioGroup) findViewById(R.id.rg_sex);
rg_Male = (RadioButton) findViewById(R.id.rb_Male);
rg_Female = (RadioButton) findViewById(R.id.rb_FeMale);
rg.setOnCheckedChangeListener(this); //绑定事件
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
switch (checkedId) {
case R.id.rb_FeMale:
// 当用户选择女性时
Log.e("chao", "onCheckedChanged: ");
Toast.makeText(this,"当前用户选择 "+ rg_Female.getText().toString(),Toast.LENGTH_SHORT).show();
break;
case R.id.rb_Male:
// 当用户选择男性时
Toast.makeText(this,"当前用户选择" +rg_Male.getText().toString(),Toast.LENGTH_SHORT).show();
break;
}
}