sharedpreferences和单选按钮我无法正确保存一个单选按钮的状态

2019年9月6日 19点热度 0条评论

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

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

onCreate

@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));

// onChecked

    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();
                }
            }