如何使用SharedPreferences保存RadioGroup状态

时间:2014-03-03 20:53:12

标签: android radio-group

我创建了一个代表问题的广播组,有4个答案选择(a,b,c和d),因此我为无线电组创建了4个单选按钮,它工作正常,但我想要的是当我离开活动并返回时,保持答案被检查,这是代码:

公共类P2扩展了Page1 {

RadioGroup rg2 ;
RadioButton r2a , r2b , r2c , r2d ;
Button b2n , b2b ;
TextView tv ;
int count ;

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

    rg2 = (RadioGroup) findViewById(R.id.RG2);
    r2a = (RadioButton) rg2.getChildAt(0);
    r2b = (RadioButton) rg2.getChildAt(1);
    r2c = (RadioButton) rg2.getChildAt(2);
    r2d = (RadioButton) rg2.getChildAt(3);
    b2n = (Button) findViewById(R.id.B2n);  // next button
    b2b = (Button) findViewById(R.id.B2b); // back button to page1
    tv = (TextView) findViewById(R.id.res);


    rg2.setOnCheckedChangeListener(new OnCheckedChangeListener(){

        @Override
        public void onCheckedChanged(RadioGroup arg0, int arg1) {
            if (r2c.isChecked()){
    count ++ ;  // since c is the correct answer add 1 to count (mark)

                          }

        }

    });


}

public void move21(View view){//当点击b2b返回第1页时调用

    Intent intent = new Intent(this , Page1.class) ;
    startActivity (intent) ;
} }
BTW,我没有为radiobuttons定义id,只是为radiogroup定义了id(rg2)。 如何使用共享首选项保存radiogroup的状态?  感谢

1 个答案:

答案 0 :(得分:0)

离开当前活动之前你可以做的是用以下内容保存状态:

SharedPreferences settings = getSharedPreferences("answers", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("r2a",r2a.isChecked());
editor.putBoolean("r2b",r2b.isChecked());
editor.putBoolean("r2c",r2c.isChecked());
editor.putBoolean("r2d",r2d.isChecked());
editor.apply();

然后,当你回到活动时,你可以这样做:

SharedPreferences settings = getSharedPreferences("answers", MODE_PRIVATE);
boolean r2achecked = settings.getBoolean("r2a",false);
boolean r2bchecked = settings.getBoolean("r2b",false);
boolean r2cchecked = settings.getBoolean("r2c",false);
boolean r2dchecked = settings.getBoolean("r2d",false);

然后检查每个新创建的bool,如果其中一个为真,则将该按钮设置为选中。