📜  如何在Android中创建测验应用程序?

📅  最后修改于: 2021-05-10 17:47:21             🧑  作者: Mango

Android是一个操作系统,基本建成的手机。它基于Linux内核和其他开源 Google开发的软件。如今,Android在学生中非常流行,学生们现在正在为他们的项目选择Android。对于初学者来说,构建婴儿Android应用程序以学习Android非常重要。在本文中,我们使用Java在android中创建一个简单的Quiz App 。一个简单的测验应用程序,其中包含一组策划的问题及其答案,并检查用户给出答案的正确性。它使用动态编程来浏览问题。

方法

步骤1:建立新专案

  • 点击 左上角的“文件”选项。
  • 然后单击新建并打开一个项目并命名该项目。
  • 现在,选择语言为Java的清空活动。
  • 将其命名为QuizApp

创建一个新项目

步骤2:使用activity_main.xml设计UI

将以下代码添加到activity_main.xml文件中。在此,父布局是一个LinearLayout,其方向设置为vertical。里面有一个ImageView ,一个TextView ,两个Button和两个 ImageButton 。 Button和ImageButton位于子LinearLayout中,用于水平方向。 ImageView用于显示图像,TextView用于显示问题,Button用于指示是/否,ImageButton用于导航到下一个/上一个问题。

可绘制文件夹中添加图像

以下是该项目中使用的所有可绘制文件的链接。

  • 对于花朵图像(f1 / f2 / f3 / f4 / f5 / f6 / f7):请参阅此。
  • 对于下一个图标:请参阅此。
  • 对于上一个图标:请参阅此。
  • 对于表情符号:请参阅此。

下面给出了activity_main.xml文件的完整代码。

activity_main.xml



  
    
    
  
    
    
  
    
    
  
        
        


Question.java
package org.geeksforgeeks.quizapp;
  
public class Question
{
    // answerResId will store question
    private int answerResId;
    
    // answerTrue will store correct answer
    // of the question provided
    private boolean answerTrue;
  
    public Question(int answerResId, boolean answerTrue)
    {
      // setting the values through
      // arguments passed in constructor
      this.answerResId = answerResId;
      this.answerTrue = answerTrue;
    }
    
    // returning the question passed
    public int getAnswerResId() 
    {
      return answerResId; 
    }
    
    // setting the question passed
    public void setAnswerResId(int answerResId)
    {
      this.answerResId = answerResId;
    }
    
    // returning the correct answer
    // of question
    public boolean isAnswerTrue() 
    {
      return answerTrue; 
    }
    
    // setting the correct
    // ans of question
    public void setAnswerTrue(boolean answerTrue)
    {
      this.answerTrue = answerTrue;
    }
}


strings.xml

    
    GFG | HOW WELL DO YOU KNOW SIMRAN?
    CORRECTNESS IS \n
                           %1$d OUT OF 6
    true
    false
    That\'s correct
    That\'s incorrect
    Simran loves Chocolates.
    Simran Knows Following Skills:\n \t
                     Ballet\n \t
                     HipHop
    Do You Think Simran Believes In:\n \t
                     Luck!!!
    Do You Think Simran Wants To Visit Italy
    Simran Loves Loyalty.
    Simran Sleeps Less
    next
    previous
  


MainActivity.java
package org.geeksforgeeks.quizapp;
  
import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity
    implements View.OnClickListener {
    // setting up things
    private Button falseButton;
    private Button trueButton;
    private ImageButton nextButton;
    private ImageButton prevButton;
    private ImageView Image;
    private TextView questionTextView;
    private int correct = 0;
    // to keep current question track
    private int currentQuestionIndex = 0;
  
    private Question[] questionBank = new Question[] {
        // array of objects of class Question
        // providing questions from string
        // resource and the correct ans
        new Question(R.string.a, true),
        new Question(R.string.b, false),
        new Question(R.string.c, true),
        new Question(R.string.d, true),
        new Question(R.string.e, true),
        new Question(R.string.f, false),
  
    };
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // setting up the buttons
        // associated with id
        falseButton = findViewById(R.id.false_button);
        trueButton = findViewById(R.id.true_button);
        nextButton = findViewById(R.id.next_button);
        prevButton = findViewById(R.id.prev_button);
        // register our buttons to listen to
        // click events
        questionTextView
            = findViewById(R.id.answer_text_view);
        Image = findViewById(R.id.myimage);
        falseButton.setOnClickListener(this);
        trueButton.setOnClickListener(this);
        nextButton.setOnClickListener(this);
        prevButton.setOnClickListener(this);
    }
  
    @SuppressLint("SetTextI18n")
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onClick(View v)
    {
        // checking which button is
        // clicked by user
        // in this case user choose false
        switch (v.getId()) {
        case R.id.false_button:
            checkAnswer(false);
            break;
  
        case R.id.true_button:
            checkAnswer(true);
            break;
  
        case R.id.next_button:
            // go to next question
            // limiting question bank range
            if (currentQuestionIndex < 7) {
                currentQuestionIndex
                    = currentQuestionIndex + 1;
                // we are safe now!
                // last question reached
                // making buttons
                // invisible
                if (currentQuestionIndex == 6) {
                    questionTextView.setText(getString(
                        R.string.correct, correct));
                    nextButton.setVisibility(
                        View.INVISIBLE);
                    prevButton.setVisibility(
                        View.INVISIBLE);
                    trueButton.setVisibility(
                        View.INVISIBLE);
                    falseButton.setVisibility(
                        View.INVISIBLE);
                    if (correct > 3)
  
                        questionTextView.setText(
                            "CORRECTNESS IS " + correct
                            + " "
                            + "OUT OF 6");
                    // showing correctness
                    else
                        Image.setImageResource(
                            R.drawable.resu);
                    // if correctness<3 showing sad emoji
                }
                else {
                    updateQuestion();
                }
            }
  
            break;
        case R.id.prev_button:
            if (currentQuestionIndex > 0) {
                currentQuestionIndex
                    = (currentQuestionIndex - 1)
                      % questionBank.length;
                updateQuestion();
            }
        }
    }
  
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void updateQuestion()
    {
        Log.d("Current",
              "onClick: " + currentQuestionIndex);
  
        questionTextView.setText(
            questionBank[currentQuestionIndex]
                .getAnswerResId());
        // setting the textview with new question
        switch (currentQuestionIndex) {
        case 1:
            // setting up image for each
            // question
            Image.setImageResource(R.drawable.f2);
            break;
        case 2:
            Image.setImageResource(R.drawable.f3);
            break;
        case 3:
            Image.setImageResource(R.drawable.f4);
            break;
        case 4:
            Image.setImageResource(R.drawable.f5);
            break;
        case 5:
            Image.setImageResource(R.drawable.f6);
            break;
        case 6:
            Image.setImageResource(R.drawable.f7);
            break;
        case 7:
            Image.setImageResource(R.drawable.f1);
            break;
        }
    }
    private void checkAnswer(boolean userChooseCorrect)
    {
        boolean answerIsTrue
            = questionBank[currentQuestionIndex]
                  .isAnswerTrue();
        // getting correct ans of current question
        int toastMessageId;
        // if ans matches with the
        // button clicked
  
        if (userChooseCorrect == answerIsTrue) {
            toastMessageId = R.string.correct_answer;
            correct++;
        }
        else {
            // showing toast
            // message correct
            toastMessageId = R.string.wrong_answer;
        }
  
        Toast
            .makeText(MainActivity.this, toastMessageId,
                      Toast.LENGTH_SHORT)
            .show();
    }
}


在activity_main.xml中添加此代码后,UI如下所示:

步骤3:处理问题。Java

要创建新的Java类,请右键单击Java文件或文件夹,然后选择新建> Java类

现在,在“问题”中添加以下代码。 Java的。这里使用getters和setters方法来检索和设置数据。方法isAnswerTrue()返回已经在Question构造函数中传递的answerTrue

问题。Java

package org.geeksforgeeks.quizapp;
  
public class Question
{
    // answerResId will store question
    private int answerResId;
    
    // answerTrue will store correct answer
    // of the question provided
    private boolean answerTrue;
  
    public Question(int answerResId, boolean answerTrue)
    {
      // setting the values through
      // arguments passed in constructor
      this.answerResId = answerResId;
      this.answerTrue = answerTrue;
    }
    
    // returning the question passed
    public int getAnswerResId() 
    {
      return answerResId; 
    }
    
    // setting the question passed
    public void setAnswerResId(int answerResId)
    {
      this.answerResId = answerResId;
    }
    
    // returning the correct answer
    // of question
    public boolean isAnswerTrue() 
    {
      return answerTrue; 
    }
    
    // setting the correct
    // ans of question
    public void setAnswerTrue(boolean answerTrue)
    {
      this.answerTrue = answerTrue;
    }
}

步骤4:使用字符串.xml文件

字符串.xml文件中,我们必须提供问题库。可以在此文件中添加许多问题。

字符串.xml


    
    GFG | HOW WELL DO YOU KNOW SIMRAN?
    CORRECTNESS IS \n
                           %1$d OUT OF 6
    true
    false
    That\'s correct
    That\'s incorrect
    Simran loves Chocolates.
    Simran Knows Following Skills:\n \t
                     Ballet\n \t
                     HipHop
    Do You Think Simran Believes In:\n \t
                     Luck!!!
    Do You Think Simran Wants To Visit Italy
    Simran Loves Loyalty.
    Simran Sleeps Less
    next
    previous
  

步骤5:使用MainActivity。Java

启动应用程序时,将首先调用onCreate()方法。 Question []数组使用问题ID和问题的正确答案进行实例化。每当单击Button / ImageButton时,都会调用setOnClickListener()方法,因此,当用户单击按钮时,它将通过getId()方法检查其ID ,并按照我们的逻辑执行操作。 updateQuestion()通过TextViewsettext()方法更新问题,并通过跟踪问题编号来更改图像。 checkAnswer()方法通过单击按钮来检查原始答案,并使用Toast相应地显示文本。

主要活动。Java

package org.geeksforgeeks.quizapp;
  
import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity
    implements View.OnClickListener {
    // setting up things
    private Button falseButton;
    private Button trueButton;
    private ImageButton nextButton;
    private ImageButton prevButton;
    private ImageView Image;
    private TextView questionTextView;
    private int correct = 0;
    // to keep current question track
    private int currentQuestionIndex = 0;
  
    private Question[] questionBank = new Question[] {
        // array of objects of class Question
        // providing questions from string
        // resource and the correct ans
        new Question(R.string.a, true),
        new Question(R.string.b, false),
        new Question(R.string.c, true),
        new Question(R.string.d, true),
        new Question(R.string.e, true),
        new Question(R.string.f, false),
  
    };
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // setting up the buttons
        // associated with id
        falseButton = findViewById(R.id.false_button);
        trueButton = findViewById(R.id.true_button);
        nextButton = findViewById(R.id.next_button);
        prevButton = findViewById(R.id.prev_button);
        // register our buttons to listen to
        // click events
        questionTextView
            = findViewById(R.id.answer_text_view);
        Image = findViewById(R.id.myimage);
        falseButton.setOnClickListener(this);
        trueButton.setOnClickListener(this);
        nextButton.setOnClickListener(this);
        prevButton.setOnClickListener(this);
    }
  
    @SuppressLint("SetTextI18n")
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onClick(View v)
    {
        // checking which button is
        // clicked by user
        // in this case user choose false
        switch (v.getId()) {
        case R.id.false_button:
            checkAnswer(false);
            break;
  
        case R.id.true_button:
            checkAnswer(true);
            break;
  
        case R.id.next_button:
            // go to next question
            // limiting question bank range
            if (currentQuestionIndex < 7) {
                currentQuestionIndex
                    = currentQuestionIndex + 1;
                // we are safe now!
                // last question reached
                // making buttons
                // invisible
                if (currentQuestionIndex == 6) {
                    questionTextView.setText(getString(
                        R.string.correct, correct));
                    nextButton.setVisibility(
                        View.INVISIBLE);
                    prevButton.setVisibility(
                        View.INVISIBLE);
                    trueButton.setVisibility(
                        View.INVISIBLE);
                    falseButton.setVisibility(
                        View.INVISIBLE);
                    if (correct > 3)
  
                        questionTextView.setText(
                            "CORRECTNESS IS " + correct
                            + " "
                            + "OUT OF 6");
                    // showing correctness
                    else
                        Image.setImageResource(
                            R.drawable.resu);
                    // if correctness<3 showing sad emoji
                }
                else {
                    updateQuestion();
                }
            }
  
            break;
        case R.id.prev_button:
            if (currentQuestionIndex > 0) {
                currentQuestionIndex
                    = (currentQuestionIndex - 1)
                      % questionBank.length;
                updateQuestion();
            }
        }
    }
  
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void updateQuestion()
    {
        Log.d("Current",
              "onClick: " + currentQuestionIndex);
  
        questionTextView.setText(
            questionBank[currentQuestionIndex]
                .getAnswerResId());
        // setting the textview with new question
        switch (currentQuestionIndex) {
        case 1:
            // setting up image for each
            // question
            Image.setImageResource(R.drawable.f2);
            break;
        case 2:
            Image.setImageResource(R.drawable.f3);
            break;
        case 3:
            Image.setImageResource(R.drawable.f4);
            break;
        case 4:
            Image.setImageResource(R.drawable.f5);
            break;
        case 5:
            Image.setImageResource(R.drawable.f6);
            break;
        case 6:
            Image.setImageResource(R.drawable.f7);
            break;
        case 7:
            Image.setImageResource(R.drawable.f1);
            break;
        }
    }
    private void checkAnswer(boolean userChooseCorrect)
    {
        boolean answerIsTrue
            = questionBank[currentQuestionIndex]
                  .isAnswerTrue();
        // getting correct ans of current question
        int toastMessageId;
        // if ans matches with the
        // button clicked
  
        if (userChooseCorrect == answerIsTrue) {
            toastMessageId = R.string.correct_answer;
            correct++;
        }
        else {
            // showing toast
            // message correct
            toastMessageId = R.string.wrong_answer;
        }
  
        Toast
            .makeText(MainActivity.this, toastMessageId,
                      Toast.LENGTH_SHORT)
            .show();
    }
}

输出:在模拟器上运行