2013-02-19 88 views
0

我有一个显示选择题测验应用程序(TextView用5 RadioButtons如下选择)作为ViewPager内的FragmentStatePagerAdapter片段。在FragmentStatePagerAdapter还原片段恢复错误

我得到的错误只有当片段恢复。向前推,它会完美加载每个问题和所有5个选择。但是,当它恢复时,它会加载完全错误,其中所有5个RadioButtons都显示相同的文本,特别是最后一个RadioButton。我不知道为什么会出现这个错误,但我认为这可能与通过超级类的调用有关,但这只是一种预感。

下面的代码:

OnCreateView设置正确,通过logcat的决定全文:

for (String s : aArray) { 
// Runs through a string array of the 5 answers 
     LinearLayout l = lArray.get(pos); 

      RadioButton r = (RadioButton) l.findViewById(R.id.radio); 
      Log.d(s, correctanswer); 
//Log tag shows that the choices during initial creation or **restore** are the different 5 answers 
      r.setText(s); 
     } 
    return rootView; 

然后,这是我的OnViewStateRestored

public void onViewStateRestored(Bundle savedInstanceState) { 
    super.onViewStateRestored(savedInstanceState); 
    for (LinearLayout l : lArray) { 
     RadioButton r = (RadioButton) l.findViewById(R.id.radio); 
     Log.e(r.getText().toString(), correctanswer); 
//Suddenly the displayed text is the same for all 5 buttons 
     if (r.isChecked()) 
      r.performClick(); 
//android automatically saves check status. for full restore I click all the buttons 
    } 
} 

如果从OnCreateView需要更多的代码或其他任何事情都让我知道。我似乎无法解决导致此问题的原因,并非常感谢您的帮助!

回答

2

您的每个单选按钮都应该有一个不同的ID,而不是它们都具有相同的ID。这就是单选按钮和其他视图如何通过id保存状态。那么,为了更准确,他们将他们的状态保存在由他们的ID映射的SparseArray中。因此,为什么他们都有第5个关于恢复的信息。

+0

没错 - android在自动保存并恢复视图状态时使用这些id,并且因为所有单选按钮都具有相同的id,导致所描述的行为。 – Ridcully 2013-02-19 20:00:55

+0

听起来合乎逻辑 - 测试:D – AndroidPenguin 2013-02-19 22:17:07

+0

就是这样:)谢谢你! – AndroidPenguin 2013-02-19 22:45:15