如何使用SharedPreference保存RadioButton状态?

时间:2017-06-02 14:54:52

标签: android radio-button sharedpreferences android-sharedpreferences android-radiobutton

这是应用视图:
enter image description here

这是我的活动代码:

public class Quiz extends AppCompatActivity {
    public static int point;
    public static int i = 0;
    RadioGroup radioGroup;
    public static int totalPoint =0;
    int arrValues[]={0,0,0,0};
    int iPosition=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);
        i = 0;
       final RadioButton radioButton1 =(RadioButton) findViewById(R.id.number_1);
        final RadioButton radioButton2 =(RadioButton) findViewById(R.id.number_2);
        final RadioButton radioButton3 =(RadioButton) findViewById(R.id.number_3);
        final RadioButton radioButton4 =(RadioButton) findViewById(R.id.number_4);
        final String[] items = getResources().getStringArray(R.array.quiz);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        Button nextButton = (Button) findViewById(R.id.button);
        Button previousButton = (Button) findViewById(R.id.button2);
        radioButton1.setText(items[0]);
        radioButton2.setText(items[1]);
        radioButton3.setText(items[2]);
        radioButton4.setText(items[3]);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()  {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) throws ArrayIndexOutOfBoundsException {
               try {
                   if (checkedId == R.id.number_1) {
                       arrValues[iPosition] = 0;
                   } else if (checkedId == R.id.number_2) {
                       arrValues[iPosition] =  1;
                   }else if (checkedId == R.id.number_3) {
                       arrValues[iPosition]=  2;
                   }else if (checkedId == R.id.number_4) {
                       arrValues[iPosition] =  3;
                   }
                   // Total
                   totalPoint = getTotalPoint();

                   Log.e("sd",""+totalPoint);
               }
                catch (ArrayIndexOutOfBoundsException sd){
                    Log.e("sd","sdsd");
                }
            }

            private int getTotalPoint() {

                int sum = 0;
                for (int i = 0; i < arrValues.length; i++)
                    sum += arrValues[i];
                Log.e("sum",""+sum);

                return sum;
            }
        });
        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                loadNextQuestion();
            }

            private void loadNextQuestion() throws ArrayIndexOutOfBoundsException {
                // Update UI
                // Clear radio button state
                try {
                    if (i>= items.length-4){
                        return;
                    }
                    iPosition++;
                    i = i + 4;
                    radioGroup.clearCheck();
                    radioButton1.setText(items[i]);
                    radioButton2.setText(items[i + 1]);
                    radioButton3.setText(items[i + 2]);
                    radioButton4.setText(items[i + 3]);
                } catch (ArrayIndexOutOfBoundsException arr) {

                }

            }
        });
        previousButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Update UI
                // Clear radio button state
                loadpreQuestion();


            }

            private void loadpreQuestion() {
                try {
                    if (i<=0){
                       return;
                    }
                    iPosition--;
                    i = i - 4;
                    radioGroup.clearCheck();
                    radioButton1.setText(items[i]);
                    radioButton2.setText(items[i + 1]);
                    radioButton3.setText(items[i + 2]);
                    radioButton4.setText(items[i + 3]);
                } catch (ArrayIndexOutOfBoundsException arr) {

                }
            }
        });
    }
    public void onRadioButtonClicked(View view)throws ArrayIndexOutOfBoundsException {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        try {

        switch(view.getId()) {
            case R.id.number_1:
                if (checked)
                    point = 0;
                Toast.makeText(this, ""+ arrValues[iPosition] ,
                        Toast.LENGTH_SHORT).show();
                // Pirates are the best
                break;
            case R.id.number_2:
                if (checked)
                    point = 1;
                Toast.makeText(this, ""+ arrValues[iPosition] ,
                        Toast.LENGTH_SHORT).show();
                // Ninjas rule
                break;
            case R.id.number_3:
                if (checked)
                    point = 2;
                Toast.makeText(this, ""+arrValues[iPosition] ,
                        Toast.LENGTH_SHORT).show();
                // Ninjas rule
                break;
            case R.id.number_4:
                if (checked)
                    point = 3;
                Toast.makeText(this, ""+ arrValues[iPosition] ,
                        Toast.LENGTH_SHORT).show();
                // Ninjas rule
                break;   }

        }
        catch (ArrayIndexOutOfBoundsException ds){}
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        i = 0;
    }


}

如您所见,一次只有4个RadioButtons,其文字只会随NextPrevious按钮而变化。那么如何在不影响其他问题的情况下使用SharedPrefrence保存RadioButton状态呢?

更新代码:

     @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) throws ArrayIndexOutOfBoundsException {
               try {
                   if (checkedId == R.id.number_1) {
                       arrValues[iPosition] = 0;
                       editor.putInt(String.valueOf(iPosition), 0);

                   } else if (checkedId == R.id.number_2) {
                       arrValues[iPosition] =  1;
                       editor.putInt(String.valueOf(iPosition), 1);
                       sharedPreferences.getInt(String.valueOf(iPosition),1);
                       int radioButtonStatusQ1 = sharedPreferences.getInt("0", 0);
                       if (radioButtonStatusQ1==1){
                           radioGroup.check(R.id.number_2);

                       }

                   }else if (checkedId == R.id.number_3) {
                       arrValues[iPosition]=  2;
                       editor.putInt(String.valueOf(iPosition), 2);
                   }else if (checkedId == R.id.number_4) {
                       arrValues[iPosition] =  3;
                       editor.putInt(String.valueOf(iPosition), 3);
                   }


                   // Commit
                   editor.commit();
                   // Total
                   totalPoint = getTotalPoint();

                   Log.e("sd",""+totalPoint);
               }
                catch (ArrayIndexOutOfBoundsException sd){
                    Log.e("sd","sdsd");
                }
            }

1 个答案:

答案 0 :(得分:0)

RadioButton状态存储到SharedPreferences,密钥为iPositioniPosition0, 1, 2, 3 ......(N-1)where N = Number of question)。

RadioButton状态存储在SharedPreferences

public class Quiz extends AppCompatActivity {

    public static int point;
    public static int i = 0;
    RadioGroup radioGroup;
    public static int totalPoint = 0;
    int arrValues[] = {0,0,0,0};
    int iPosition = 0;

    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        .......
        .............

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = sharedPreferences.edit();

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()  {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) throws ArrayIndexOutOfBoundsException {
               try {
                   if (checkedId == R.id.number_1) {
                       arrValues[iPosition] = 0;
                       editor.putInt(String.valueOf(iPosition), 0);
                   } else if (checkedId == R.id.number_2) {
                       arrValues[iPosition] =  1;
                       editor.putInt(String.valueOf(iPosition), 1);
                   }else if (checkedId == R.id.number_3) {
                       arrValues[iPosition]=  2;
                       editor.putInt(String.valueOf(iPosition), 2);
                   }else if (checkedId == R.id.number_4) {
                       arrValues[iPosition] =  3;
                       editor.putInt(String.valueOf(iPosition), 3);
                   }

                   // Commit changes
                   editor.commit();

                   // Total
                   totalPoint = getTotalPoint();

                   Log.e("sd",""+totalPoint);
               }
                catch (ArrayIndexOutOfBoundsException sd){
                    Log.e("sd","sdsd");
               }
            }
        });

    }

    ............
    ...............

}

RadioButton获取SharedPreferences状态:

int radioButtonStatusQ1 = sharedPreferences.getInt("0", 0);
int radioButtonStatusQ2 = sharedPreferences.getInt("1", 0);
........
..................