问题是当发生方向改变时,不仅寻呼机而且适配器被重新加载 – 我知道如何保存当前的寻呼机位置,但是当适配器被重置时,它也从该组中选择新的问题.处理这个问题的正确方法是什么?
另外,附带问题 – 在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; } }
解决方法
I know how to save the current pager position but when the adapter
gets reset,it also chooses new questions from the set. What would be
the proper way to handle this?
您的问题应该具有唯一标识它们的ID.我不确定你是如何从数据库中获取它们的,但是当发生这种情况时你需要存储它们的ID.也:
>您的适配器应该有一个长数组(或整数),其中包含30个值,表示当前所选批次问题的ID
>您需要在适配器中实现以下逻辑:如果前一点的长数组为null,则假设它是一个干净的开始并获得一组新的30个问题.
如果long数组为非null,那么我们将面临从配置更改中恢复,您需要使用这些ID来从数据库中获取正确的问题,而不是随机批处理
>在Activity中,您将在onSaveInstanceState()方法中保存适配器的长数组(savedInstanceState.putLongArray)
>在Activity的onCreate方法中,当您创建适配器时,您将检查savedInstanceState Bundle以查看它是否为非null并且它具有long数组并在适配器上设置它(因此它将知道哪些问题到得到)
what would be the best way to register the choices on the RadioGroups?
Directly by click or in a different way?