如何使用 SharedPreference 保存 RadioButton 状态? [英] How to save RadioButton status with SharedPreference?

本文介绍了如何使用 SharedPreference 保存 RadioButton 状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是应用视图:

这是我的活动代码:

public class Quiz extends AppCompatActivity {公共静态整数点;公共静态 int i = 0;RadioGroup radioGroup;public static int totalPoint =0;int arrValues[]={0,0,0,0};int iPosition=0;@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_quiz);我 = 0;最终 RadioButton radioButton1 =(RadioButton) findViewById(R.id.number_1);最终 RadioButton radioButton2 =(RadioButton) findViewById(R.id.number_2);最终 RadioButton radioButton3 =(RadioButton) findViewById(R.id.number_3);最终 RadioButton radioButton4 =(RadioButton) findViewById(R.id.number_4);final String[] items = getResources().getStringArray(R.array.quiz);radioGroup = (RadioGroup) findViewById(R.id.radioGroup);按钮 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() {@覆盖public void onCheckedChanged(RadioGroup group, int checkedId) 抛出 ArrayIndexOutOfBoundsException {尝试 {如果(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;}//全部的totalPoint = getTotalPoint();Log.e("sd",""+totalPoint);}捕获(ArrayIndexOutOfBoundsException sd){Log.e("sd","sdsd");}}私有 int getTotalPoint() {整数总和 = 0;for (int i = 0; i < arrValues.length; i++)总和 += arrValues[i];Log.e("sum",""+sum);返还金额;}});nextButton.setOnClickListener(new View.OnClickListener() {@覆盖public void onClick(View v) {加载下一个问题();}私有无效 loadNextQuestion() 抛出 ArrayIndexOutOfBoundsException {//更新界面//清除单选按钮状态尝试 {if (i>= items.length-4){返回;}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() {@覆盖public void onClick(View v) {//更新界面//清除单选按钮状态loadpreQuestion();}私人无效loadpreQuestion(){尝试 {如果 (i<=0){返回;}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 {//按钮现在是否被选中?布尔检查 = ((RadioButton) 视图).isChecked();//检查哪个单选按钮被点击尝试 {开关(视图.getId()){案例 R.id.number_1:如果(选中)点 = 0;Toast.makeText(this, ""+ arrValues[iPosition] ,Toast.LENGTH_SHORT).show();//海盗是最好的休息;案例 R.id.number_2:如果(选中)点 = 1;Toast.makeText(this, ""+ arrValues[iPosition] ,Toast.LENGTH_SHORT).show();//忍者规则休息;案例 R.id.number_3:如果(选中)点 = 2;Toast.makeText(this, ""+arrValues[iPosition] ,Toast.LENGTH_SHORT).show();//忍者规则休息;案例 R.id.number_4:如果(选中)点 = 3;Toast.makeText(this, ""+ arrValues[iPosition] ,Toast.LENGTH_SHORT).show();//忍者规则休息;}}catch (ArrayIndexOutOfBoundsException ds){}}@覆盖公共无效 onBackPressed() {super.onBackPressed();我 = 0;}}

如您所见,一次只有 4 个 RadioButton,它们的文本仅随 NextPrevious 按钮而变化.那么如何在不影响其他问题的情况下使用 SharedPrefence 保存 RadioButton 状态?

更新代码:

 @Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) 抛出 ArrayIndexOutOfBoundsException {尝试 {如果(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);如果(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);}//犯罪editor.commit();//全部的totalPoint = getTotalPoint();Log.e("sd",""+totalPoint);}捕获(ArrayIndexOutOfBoundsException sd){Log.e("sd","sdsd");}}

解决方案

使用 KEY iPosition 将您的 RadioButton 状态存储到 SharedPreferences>iPosition0, 1, 2, 3 ......(N-1) (where N = Number of question).>

SharedPreferences 中存储 RadioButton 状态:

public class Quiz extends AppCompatActivity {公共静态整数点;公共静态 int i = 0;RadioGroup radioGroup;公共静态 int totalPoint = 0;int arrValues[] = {0,0,0,0};int iPosition = 0;SharedPreferences sharedPreferences;SharedPreferences.Editor 编辑器;@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);......………………sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);编辑器 = sharedPreferences.edit();radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@覆盖public void onCheckedChanged(RadioGroup group, int checkedId) 抛出 ArrayIndexOutOfBoundsException {尝试 {如果(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);}//提交更改editor.commit();//全部的totalPoint = getTotalPoint();Log.e("sd",""+totalPoint);}捕获(ArrayIndexOutOfBoundsException sd){Log.e("sd","sdsd");}}});}……………………………………}

SharedPreferences 获取 RadioButton 状态:

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

This is the app view:

and here is my activity code:

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


}

As you see there are only 4 RadioButtons at a time and their text just change with Next and Previous buttons. So how can I save RadioButton status with SharedPrefrence without affecting other questions?

UPDATE CODE:

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

解决方案

Store your RadioButton status into SharedPreferences with KEY iPosition and iPosition is 0, 1, 2, 3 ......(N-1) (where N = Number of question).

Store RadioButton status in 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");
               }
            }
        });

    }

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

}

Get RadioButton status from SharedPreferences:

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

这篇关于如何使用 SharedPreference 保存 RadioButton 状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆