我正在努力实现单选按钮的sharedpreference,我试图保存单选按钮的状态,但是当我运行模拟器时,出现空白屏幕,并且页面上的所有内容都消失了……任何帮助将不胜感激。

这是我的代码:

在创建

public void onCreate(Bundle savedInstanceState, ViewGroup radioGroup) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_system);
    SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
    int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
    RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
    savedCheckedRadioButton.setChecked(true);


调用方法

    RadioGroup gender = (RadioGroup) findViewById(R.id.question1);

    gender.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub
            switch (checkedId) {
            case R.id.answer1A:
                ans1 = 1;
                break;
            case R.id.answer1B:
                ans1 = 2;
                break;
            }
            SavePreferences("SAVED_RADIO_BUTTON_INDEX", checkedId);

        }


方法

        private void SavePreferences(String key, int value){
              SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
              SharedPreferences.Editor editor = sharedPreferences.edit();
              editor.putInt(key, value);
              editor.commit();
             }

    });

最佳答案

我认为您正在尝试将id设置为position,请尝试

     SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
     int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX,R.id.answer1A);
     gender.check(savedRadioIndex);


代替

    SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
    int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
    RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
    savedCheckedRadioButton.setChecked(true);

08-06 08:11