首页 > 解决方案 > 虽然我只想选择一个,但可以选择两个单选按钮

问题描述

我正在制作一个 android 应用程序,在应用程序中可以选择一次两个单选按钮。但我只想选择一个。我应该编码什么?

public class ProfileManagement extends AppCompatActivity {
    private Button update;
    private EditText uname, dob, pass;
    private RadioButton male, female;
    private DBHelper dbHelper;
    private String userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_management);

        dbHelper = new DBHelper(this);
        Intent intent = getIntent();
        userId = intent.getStringExtra("id");

        uname = findViewById(R.id.user);
        dob = findViewById(R.id.date);
        pass = findViewById(R.id.word);
        update = findViewById(R.id.btnUpdate);
        male = findViewById(R.id.radioMale);
        female = findViewById(R.id.radioFe);

        ArrayList<User> list =  dbHelper.readAllInfo(userId, null);

        for (User u : list){

            uname.setText(u.getUserName());
            pass.setText(u.getPassword());
            dob.setText(u.getDateOfBirth());

这是我检查单选按钮的方式。这个可以吗?

if(u.getGender() != null){
        if(u.getGender().equals("Male")){

                male.setChecked(true);
            }
            else
            {
                female.setChecked(true);
            }      } }
    update.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(ProfileManagement.this, EditProfile.class);
            intent.putExtra("id", userId);
            startActivity(intent);
        }          });      }  }

标签: androidradio-button

解决方案


像这样使用广播组:

<RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text"
        android:id="@+id/myRadioGroup"
        android:background="#abf234"
        android:checkedButton="@+id/sound" >
         
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/sound"
            android:text="@string/Sound" />
         
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/vibration"
            android:text="@string/Vibration" />
         
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/silent"
            android:text="@string/Silent" />
        
</RadioGroup>

然后检查哪个按钮被点击了使用下面的代码:

radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(RadioGroup rGroup, int checkedId) {

        int radioBtnID = rGroup.getCheckedRadioButtonId();

        View radioB = rGroup.findViewById(radioBtnID);

        int position = group.indexOfChild(radioB);
    }
});

推荐阅读