我正在使用一个ViewPager
选择题考试应用程序,它从更大的集合中随机选择三十个问题。我在PageAdapter
将页面提供给ViewPager
.
问题是,当方向发生变化时,不仅寻呼机而且适配器都会重新加载 - 我知道如何保存当前寻呼机位置,但是当适配器重置时,它还会从集合中选择新问题。处理这个问题的正确方法是什么?
另外,附带问题 - 在 RadioGroups 上注册选择的最佳方式是什么?直接通过点击还是以其他方式?
我对 Android 应用程序开发相当陌生。
活动:
public class MyActivity extends SherlockActivity {
ActionBar actionBar;
ViewPager pager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pager = new ViewPager(this);
setContentView(pager);
QuestionsAdapter adapter = new QuestionsAdapter(this);
pager.setAdapter(adapter);
int position = 0;
if (savedInstanceState != null) {
position = savedInstanceState.getInt("Q_NUMBER");
}
pager.setCurrentItem(position);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
int position = pager.getCurrentItem();
savedInstanceState.putInt("Q_NUMBER", position);
}
}
适配器:
class QuestionsAdapter extends PagerAdapter {
Context context;
QuestionsHelper dbQuestions;
boolean exam;
List<HashMap<String,Object>> examQuestions;
public QuestionsAdapter(Context context, boolean exam) {
this.context = context;
this.examQuestions = GetQuestionsFromDB(30);
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view;
HashMap<String,Object> q;
view = inflater.inflate(R.layout.exam_question_layout, null);
q = getQuestion(position+1);
((TextView)view.findViewById(R.id.q_number)).setText(Integer.toString(position+1)+".");
((TextView)view.findViewById(R.id.q_question)).setText(q.get("question").toString());
((RadioButton)view.findViewById(R.id.q_answer_a)).setText(q.get("answer_a").toString());
((RadioButton)view.findViewById(R.id.q_answer_b)).setText(q.get("answer_b").toString());
((RadioButton)view.findViewById(R.id.q_answer_c)).setText(q.get("answer_c").toString());
((ViewPager)collection).addView(view, 0);
return view;
}
}