共享首选项和单选按钮我无法正确保存一个单选按钮状态



正如标题所说,由于某种原因我无法使其工作 我尝试调试但找不到问题,每次单击radio_button_B时它都会卡在上面并且永远不会更改为radio_button_A

static RadioGroup radio_group;
RadioButton radio_button_A;
RadioButton radio_button_B;
private SharedPreferences sp_for_radio;

创建

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

//id

radio_group = findViewById(R.id.radio_group);
radio_button_A = findViewById(R.id.team_a_radio);
radio_button_B = findViewById(R.id.team_b_radio);

//SP getBoolean

sp_for_radio  = getSharedPreferences("sp_radio", MODE_PRIVATE);
radio_button_A.setChecked(sp_for_radio.getBoolean("team_a_rb", false));
radio_button_B.setChecked(sp_for_radio.getBoolean("team_b_rb", false));

//上已检查

radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
SharedPreferences.Editor editor2 = sp_for_radio.edit();
RadioButton checkedRadioButton = group.findViewById(checkedId);
// This puts the value (true/false) into the variable
boolean isChecked = checkedRadioButton.isChecked();
//
if (isChecked) {
if (radio_button_A.getId()==checkedRadioButton.getId()){
editor2.putBoolean("team_a_rb", isChecked);
editor2.apply();
}else if (radio_button_B.getId() == checkedRadioButton.getId()){
editor2.putBoolean("team_b_rb", isChecked);
editor2.apply();
}
}
}
});

}

编辑 :

如果(已选中({

if (radio_button_A.getId()==checkedRadioButton.getId()){
editor2.putBoolean("team_a_rb", isChecked);
editor2.putBoolean("team_b_rb", false);
editor2.apply();
}else if (radio_button_B.getId() == checkedRadioButton.getId()){
editor2.putBoolean("team_b_rb", isChecked);
editor2.putBoolean("team_a_rb", false);
editor2.apply();
}
}

最新更新