Android: Save State of Radio Buttons

前端 未结 3 521
梦如初夏
梦如初夏 2020-12-21 02:20

Hi I\'m trying to create an app for Android and in order to develop it i need to navigate through different pages and questions. For this task I have defined a radiogroup wi

相关标签:
3条回答
  • 2020-12-21 02:36

    i just solved this problem , now i am able to save the current state of radio button on every next click and on every previous click i get back the radio state,even at the if the user changed the state by going to previous question or any of the question.

    0 讨论(0)
  • 2020-12-21 02:38

    I'm working on same application and the solution is that you have to store state of Radio button according to your question Number and for each question there is different key, like this:

    final RadioButton rdSelection=(RadioButton)findViewById(mradioOptGroup.getCheckedRadioButtonId());
    int child_index=mradioOptGroup.indexOfChild(rdSelection);
    
    switch(mid)
    {
        case 1: 
            sharedpreferences.putint("",child_index);
            break;
        case 2:
           sharedpreferences.putint("",child_index);
           break;
    }
    

    and do like this for all your questions on every next question

    and on every previous question you have to store state of radio button of mid+1

    where mid is your question number

    0 讨论(0)
  • 2020-12-21 02:48

    If I understand you correctly, you want to retrieve some data in other activities. In that case the easiest way would be to use SharedPreferences.

    After user answers the question (CheckBox's check state is being changed) you should store your information in SharedPreferences like this:

      SharedPreferences settings = getSharedPreferences("Answers", 0); // first argument is just a name of your SharedPreferences which you want to use. It's up to you how you will name it, but you have to use the same name later when you want to retrieve data.
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("questionA", radBotA.isChecked()); // first argument is a name of a data that you will later use to retrieve it and the second argument is a value that will be stored
      editor.putBoolean("questionB", radBotB.isChecked());
      editor.putBoolean("questionC", radBotC.isChecked());
      editor.putBoolean("questionD", radBotD.isChecked());
    
      editor.commit(); // Commit the changes
    

    So now you have those information stored in your internal storage. In other activity, you can retrieve this information:

      SharedPreferences settings = getSharedPreferences("Answers", 0);
      boolean answerA = settings.getBoolean("questionA", false); // The second argument is a default value, if value with name "questionA" will not be found
      boolean answerB = settings.getBoolean("questionB", false);
      boolean answerC = settings.getBoolean("questionC", false);
      boolean answerD = settings.getBoolean("questionD", false);
    
    0 讨论(0)
提交回复
热议问题