2015-10-13 2 views
0

Я делаю викторину. У меня есть 5 вопросов, и каждый вопрос содержит 4 варианта (радиогруппа) с предыдущей и следующей кнопками. Мне нужно, когда пользователь выбирает ответ и переходит к следующему вопросу и снова возвращается к предыдущему вопросу, какой пользователь выбрал ранее, что ответ должен быть в выбранном состоянии. Пожалуйста, любой может помочь мне. Я новичок в android ..Как удерживать выбранное значение переключателя?

public class MainActivity extends AppCompatActivity { 
     List<Questions> quesList; 
     int score=0; 
     int qid; 
     Questions currentQ; 
     TextView tv; 
     RadioButton rb1,rb2,rb3,rb4; 
     ImageButton next,back; 
     RadioGroup grp; 
     Questions cur; 
     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
      DbHelper db=new DbHelper(this); 
      grp=(RadioGroup) findViewById(R.id.radiogroup1); 
      quesList=db.getAllQuestions(); 
      if(quesList!= null && quesList.size() !=0) { 
       currentQ=quesList.get(qid); 
      } 

      tv=(TextView) findViewById(R.id.tv1); 
      rb1=(RadioButton) findViewById(R.id.radio1); 
      rb2=(RadioButton) findViewById(R.id.radio2); 
      rb3=(RadioButton) findViewById(R.id.radio3); 
      rb4=(RadioButton) findViewById(R.id.radio4); 

      next=(ImageButton) findViewById(R.id.forward); 
      back=(ImageButton) findViewById(R.id.backward); 
      setQuestionView(); 
      next.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 


        RadioButton answer=(RadioButton) findViewById(grp.getCheckedRadioButtonId()); 
        if(currentQ.getAnswer().equals(answer.getText())) 
        { 
         score++; 
         Log.d("score", "Your score" + score); 
        } 

        if(qid<4){ 

         qid++; 
         currentQ=quesList.get(qid); 

         grp.clearCheck(); 
         setQuestionView(); 



        }else{ 
         Intent intent = new Intent(MainActivity.this, ResultActivity.class); 
         Bundle b = new Bundle(); 
         b.putInt("score", score); //Your score 
         intent.putExtras(b); //Put your score to your next Intent 
         startActivity(intent); 
         finish(); 
        } 

       } 
      }); 

      back.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        if(qid>0){ 
         qid--; 
         currentQ=quesList.get(qid); 
         setQuestionView(); 


        } 
       } 
      }); 
     } 

     @Override 
     public boolean onCreateOptionsMenu(Menu menu) { 
      // Inflate the menu; this adds items to the action bar if it is present. 
      getMenuInflater().inflate(R.menu.menu_main, menu); 
      return true; 
     } 
     private void setQuestionView() 
     { 
      tv.setText(currentQ.getQuestion()); 
      rb1.setText(currentQ.getOption1()); 
      rb2.setText(currentQ.getOption2()); 
      rb3.setText(currentQ.getOption3()); 
      rb4.setText(currentQ.getOption4()); 


     } 

     @Override 
     public boolean onOptionsItemSelected(MenuItem item) { 
      // Handle action bar item clicks here. The action bar will 
      // automatically handle clicks on the Home/Up button, so long 
      // as you specify a parent activity in AndroidManifest.xml. 
      int id = item.getItemId(); 

      //noinspection SimplifiableIfStatement 
      if (id == R.id.action_settings) { 
       return true; 
      } 
      return super.onOptionsItemSelected(item); 
     } 

    } 

ответ

2

Вы можете определить array или list хранить ответы и первоначально назначать 0s и когда пользователь выбирает ответ для любого заданного вопрос answers[qid] = //answer 1,2,3,4 и, наконец, изменить ваш setQuestionView() на

private void setQuestionView() 
    { 
     tv.setText(currentQ.getQuestion()); 
     rb1.setText(currentQ.getOption1()); 
     rb2.setText(currentQ.getOption2()); 
     rb3.setText(currentQ.getOption3()); 
     rb4.setText(currentQ.getOption4()); 
     switch(answers[qid]){ 
      case 1: 
       rb1.setChecked(true); 
       break; 
      case 2: 
       rb2.setChecked(true); 
       break; 
      ........... 
      default: 
       break; 
     } 

    } 

P.S Я бы не рекомендовал вышеуказанный метод, вместо этого я бы предложил повторное внедрение/факторинг вашего кода, чтобы задействовать это поведение.

+0

А также отслеживать результаты. и убедитесь, что вы не получаете награды за несколько вопросов за один правильный вопрос. – Minato

0

Когда вы дадите ответ, то получите кнопку радио идентификатор и сохранить в Arraylist, , в котором перечислите вас в настоящее время используется для показа вопроса.

Например: singleton.globalList.get (Constants.GlobalPostion). setAnswer_type ("" + buttonID);

И если поставить условие в OnCreate метода, проверьте, если вы дали на вопрос, если да, то получить значение из списка и установить, что идентификатор истинного.

Для экс:

if (isSolve()) 
    { 
      buttonID=**get id which you have been saved in arraylist**.........getAnswer_type()); 
     RadioButton btn = (RadioButton) rg.getChildAt(buttonID); 
     btn.setChecked(true); 
    } 

надеюсь, что это поможет.

0

Try что-то вроде этого

private void save(int radioid,final boolean isChecked) { 

SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedPreferences.edit(); 
editor.putBoolean("check"+radioid, isChecked); 
editor.commit(); 
} 

и получить значения

private void load() { 
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE); 
for(int i=0;i<radioGroup.getChildCount();i++){ 
    RadioButton rbtn=(RadioButton)radioGroup.getChildAt(i); 
    rbtn.setChecked(sharedPreferences.getBoolean("check"+rbtn.getId(), false)); 
} 
}