2014-02-21 2 views
-2

Я разрабатываю приложение для Android для студентов, которые могут сдавать экзамены и экзамены. Мой вопрос в том, что у меня есть множество вопросов, которые говорят 50, каждый из которых имеет 4 варианта ответа в выбираемом виде списка. Теперь, что я хочу спросить, что я хочу, чтобы их вызывали только в одном действии, а не 50, чтобы активировать активность. вот пример кодаТип экзамена android app

/***ArrayList goes here*****/ 
    stuff.add("I'm noting."); 
stuff.add("I always do nthing."); 
stuff.add("All my efforts"); 

lv = (ListView) findViewById(R.id.list); 

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
     this, 
     android.R.layout.simple_list_item_1,stuff); 
    lv.setAdapter(arrayAdapter); 

    Button sbt=(Button)findViewById(R.id.sbt); 
    sbt.setOnClickListener(new View.OnClickListener() { 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     Intent i=new Intent(getApplicationContext(),Screen5cActivity.class); 
     startActivity(i); 
    } 
    }); 

Таким образом, один способ сделать это, что приходит на ум, что взять статический счетчик и продолжают воссоздавать ту же самую деятельность, раздувая данные же ArrayList, но этот метод получает немного обфусцированный как для хранения результата, так и для другого. Любые другие решения с эффективностью и лучшими объяснениями приветствуются.

+0

Это как игра-викторина. См. [Здесь] (http://code.tutsplus.com/tutorials/android-ui-workshop-build-an-interactive-quiz-app--mobile-14208) –

+0

Вы можете хранить вопросы и их выбор, и coorect один и т. д. в базе данных sqlite и просто использовать при работе с listView, а данные списка будут выбраны из базы данных. –

+0

. Я отправлю лучший способ приблизиться к этому в ближайшее время. Вероятно, вы должны использовать основное действие, которое будет обрабатывать все различные тесты, а затем иметь общий фрагмент, который отображает разные вопросы. Тогда просто у вас активность отслеживает неправильные и правильные ответы –

ответ

1

Хорошо, вот как это сделать.

создать MainActivity следующим образом:

public class MainActivity extends FragmentActivity implements QuestionAnswerInterface{ 

private static final String FRAGMENT_TAG = "QuestionAnswerFragment"; 

private String [] questionsArray = {"How old was John Wayne when he died ?","Who was the First U.S. President ?", "How many vertices are on a Octagon ?"}; 

private String [][] answers = {{"43","56","34","none of these"}, 
           {"George Bush","Barrack Obama","George Washington","none of these"}, 
           {"6","4","8","none of these"} 
           }; 

private QuestionAnswerFragment fragment     = null; 
private ArrayList<ArrayList<String>> answersListOfLists = null; 
private ArrayList<String> answersList     = null; 
private ArrayList<String> questionsList     = null; 

// Ultimate Holder to Link the ArrayLists 
private HashMap<ArrayList<String>, ArrayList<ArrayList<String>>> questionAnswerList = null; 

@Override protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // -------- Setup the Questions ------- 
    setupQuestions(questionsArray, answers); 

    FragmentManager fm = getSupportFragmentManager(); 
    FragmentTransaction ft = fm.beginTransaction(); 

    if(fragment == null) 
    { 
     // Create the Fragment 
     fragment = (QuestionAnswerFragment) QuestionAnswerFragment.newInstance(new Bundle(), "Test Example" , questionAnswerList); 

     ft.add(R.id.frameLayoutTest, fragment, FRAGMENT_TAG); 
     ft.commit(); 

    }else{ 

     fragment = (QuestionAnswerFragment) fm.findFragmentByTag(FRAGMENT_TAG); 
     ft.show(fragment); 

    } 


} 

private void setupQuestions(String [] questions, String[][] answers) 
{ 
    // The Ultimate Wrapper 
    questionAnswerList = new HashMap<ArrayList<String>, ArrayList<ArrayList<String>>>(); 

    // ArrayList to hold the List of lists of answers 
    answersListOfLists = new ArrayList<ArrayList<String>>(); 

    // ArrayList to hold the list of Questions 
    questionsList = new ArrayList<String>(); 

    // Loop Through the Questions 
    for(int i = 0; i < questionsArray.length ; i++) 
    { 
     // Add them to the List 
     questionsList.add(questions[i]); 
    } 


    //*** Magic Stuff *** 
    for(int l = 0; l < answers.length ; l++) 
    { 
     // Needs to be created each time we add a new set of answers  
     answersList = new ArrayList<String>(); 

     // Loop through the inner array values 
     for(int m = 0; m < answers[l].length ; m++) 
     { 
      // Add the Answers for index l using values of index m 
      answersList.add(answers[l][m]); 

     } 

     answersListOfLists.add(answersList); 

    } 

    questionAnswerList.put(questionsList, answersListOfLists); 
} 

@Override 
public void sendBackAnswer(String answer) { 
    // TODO Auto-generated method stub 

} 



} 

А потом мой фрагмент Класс:

public class QuestionAnswerFragment extends Fragment{ 

private static HashMap<ArrayList<String>, ArrayList<ArrayList<String>>> m_questionAnswerList; 
private static String m_textName = null; 

private static final String TAG = "QuestionAnswerFragment"; 
private QuestionAnswerInterface m_callBack = null; 

private AnswerAdapter m_adapter   = null; 
private ArrayList<ArrayList<String>> m_answers = null; 
private ArrayList<String> m_questions = null; 

private int m_questionCount    = 0; 
private String currentQuestion   = null; 

private Entry<ArrayList<String>, ArrayList<ArrayList<String>>> entry = null; 
private Iterator<Entry<ArrayList<String>, ArrayList<ArrayList<String>>>> iterator = null; 

// UI Elements 
private ListView m_listViewAnswers  = null; 
private Button m_buttonSubmitAnswer  = null; 
private TextView m_textViewQuestion  = null; 

// ---------------------------------------------------------------------------- 
// Interface 

public interface QuestionAnswerInterface 
{ 
    // Returns the Right or wrong Answer to be kept for score calculation 
    public abstract void sendBackAnswer(String answer); 

} 


// Instance Method, so we can share the relevant information with the fragment 
public static QuestionAnswerFragment newInstance(Bundle args, String testName, HashMap<ArrayList<String>, ArrayList<ArrayList<String>>> questionAnswerList) 
{ 
    QuestionAnswerFragment fragment = new QuestionAnswerFragment(); 

    m_textName = testName; 
    m_questionAnswerList = questionAnswerList; 

    fragment.setArguments(args); 

    return fragment; 
} 

// -------------------------------------------------------------------------- 
// Class Overrides 

@Override public void onAttach(Activity activity) 
{ 
    // Default Behavior 
    super.onAttach(activity); 

    try{ 

     // Attach the Interface to the Parent Activity 
     m_callBack = (QuestionAnswerInterface) activity; 

    }catch(ClassCastException ex){ 

     // Log the Error 
     Log.d(TAG, "Failed to Implement Interface in the Parent Activity " + ex.getMessage()); 
    } 
} 

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{ 
    // Inflate the Layout from the XML Resource 
    return inflater.inflate(R.layout.question_answer_fragment, null); 
} 

@Override public void onActivityCreated(Bundle savedInstanceState) 
{ 
    // TODO Auto-generated method stub 
    super.onActivityCreated(savedInstanceState); 

    // Get a Reference to All the Views 
    m_listViewAnswers  = (ListView) getView().findViewById(R.id.listViewAnswerOptions); 
    m_textViewQuestion  = (TextView) getView().findViewById(R.id.textViewQuestion); 
    m_buttonSubmitAnswer = (Button) getView().findViewById(R.id.buttonDone); 

    // Add a Listener to the button & ListView 
    m_buttonSubmitAnswer.setOnClickListener(SubmitListener); 
    m_listViewAnswers.setOnItemSelectedListener(AnswerListener); 

    iterator = m_questionAnswerList.entrySet().iterator(); 

    // Start the test from the Beginning using the String [0] as the first question 
    entry = iterator.next(); 
    m_questions = entry.getKey();      
    m_answers = entry.getValue(); 

    Log.d("ArraySize Questions", "Size of the Questions Array is "+ m_questions.size()); 
    Log.d("ArraySize Answers", "Size of the Answers Array is "+ m_answers.size()); 


    // Start the Test 
    updateTest(); 
} 

public void updateTest() 
{ 
    m_textViewQuestion.setText(m_questions.get(m_questionCount)); 


    updateAdapter(m_answers.get(m_questionCount)); 

    m_questionCount += 1; 

} 

private void updateAdapter(ArrayList<String> arrayList) 
{ 
     m_adapter = new AnswerAdapter(getActivity(), arrayList); 
     m_listViewAnswers.setAdapter(m_adapter);  
} 

private OnItemSelectedListener AnswerListener = new OnItemSelectedListener() 
{ 

    @Override public void onItemSelected(AdapterView<?> adapter, View view, int position, long id) 
    { 
     // Get the Position of the List Item Selected 
     // Check if its correct or do what you need to do. 
     m_callBack.sendBackAnswer(m_listViewAnswers.getSelectedItem().toString()); 
    } 

    @Override public void onNothingSelected(AdapterView<?> arg0) { } 

}; 


// Submits the Answer to the Parent Activity  
private OnClickListener SubmitListener = new OnClickListener() 
{ 

    @Override public void onClick(View view) 
    { 
     if(m_questionCount != m_questions.size()) 
     { 
      // Notify the Parent that we want to share the Users choice 
      updateTest(); 
     }else{ 

      Toast.makeText(getActivity(), "You have reached the End of the Test", Toast.LENGTH_LONG).show(); 
     } 
    } 

}; 

} 

И, наконец, адаптер класса

public class AnswerAdapter extends BaseAdapter{ 


//---------------------------------------------------------- 
// Member Variables 
private Context m_classContext  = null; 
private ArrayList<String> m_answers = null; 
private LayoutInflater m_inflater = null; 

//---------------------------------------------------------- 
// Constructor 
public AnswerAdapter(Activity activity, ArrayList<String> answers) 
{ 
    this.m_classContext = activity; 
    this.m_answers = answers; 

    this.m_inflater = LayoutInflater.from(m_classContext); 

} 

// RowContainer 
public class Row 
{ 
    TextView m_textAnswer; 
    CheckBox m_selectedAnswer; 
} 

// --------------------------------------------------------- 
// Class Overrides 

@Override public int getCount() 
{ 
    int count = 0; 

    if(m_answers.size() > 0) 
    { 
     count = m_answers.size(); 
    } 

    return count; 
} 

@Override public Object getItem(int position) 
{ 
    // return the Item at the current position 
    return m_answers.get(position); 
} 

@Override public long getItemId(int position) 
{ 
    // Return the current items position 
    return position; 
} 

@Override public View getView(int position, View convertView, ViewGroup parent) 
{ 
    Row theRow ; 

    if(convertView == null){ 

     theRow = new Row(); 

     convertView = m_inflater.inflate(R.layout.answer_row_item, null); 
     theRow.m_textAnswer = (TextView) convertView.findViewById(R.id.textViewAnswer); 
     theRow.m_selectedAnswer = (CheckBox) convertView.findViewById(R.id.checkBoxAnswer); 

     convertView.setTag(theRow); 

    }else{ 
     theRow = (Row) convertView.getTag(); 
    } 

    theRow.m_textAnswer.setText(m_answers.get(position).toString()); 

    return convertView; 
} 

} 

Так вот, как я бы подойти к этому ,

Используйте Основное действие для создания новых тестов, а затем используйте интерфейс для совместного использования результатов с родителем, чтобы вы могли рассчитать итоговые значения и баллы.

0

создать один класс Pojo с переменными question.ans1 для Отв4

i.e 
    class Question{ 
    String question; 
    String ansOne; 
    String ansTwo; 
    String ansThree; 
     String ansFour; 
    String correctAns; 
    String selectedAnswer; 

} 

Теперь генерировать ArrayList с 50 вопросов;

ArrayList list = new ArrayList();

теперь генерирует просмотр списка с одним текстовым видом на вопрос и четырьмя флажками для 4 ответов.

+1

Это не отвечает на вопрос ... – 2Dee

Смежные вопросы