Приложение Android Quiz - RadioGroup и CheckBox

Я написал XML для приложения-викторины.

Будет (10) вопросов, несколько RadioGroup и несколько CheckBox, но типы вопросов не будут располагаться в любом порядке. Итак, 1-я радиогруппа, 2-й флажок, 3-я, 4-я и 5-я радиогруппа, 6-я и 7-я флажки и т. Д.

Очевидно, что RadioGroup имеет только один правильный ответ, а CheckBox имеет два или три правильных ответа.

Я хочу создать кнопку «ПРОВЕРИТЬ ВИКТОРИНУ», которая отображает сообщение в верхней части прокручиваемой викторины с правильным числом, а также отображение большого красного «X» в красном цвете перед каждым неправильным ответом.

Я не уверен, с чего начать Java-код в моем java-файле MainActivity.


MainActivity.java


package com.example.android.quiztest;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.EditText;
import android.widget.TextView;

/**
 * package com.example.android.quiztest;
 * This app displays a radio button and checkbox quiz, and then grades the quiz, *  displaying the score and identifying the incorrect answers.
 **/

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.example.android.quiztest.R.layout.activity_main);
    }
}

activity_main.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.android.quiztest.MainActivity"
    android:fillViewport="false">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="@dimen/dimension_1"
        android:orientation="vertical">


        <EditText
            android:id="@+id/name_text_view_STUDENT"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/text_person_name"
            android:inputType="textPersonName" />

        <TextView
            android:id="@+id/label_text_view_DIRECTIONS"
            style="@style/HeaderTextStyle"
            android:textSize="20sp"
            android:layout_marginTop="@dimen/dimension_1"
            android:text="@string/text_directions" />


        <TextView
            android:id="@+id/label_text_view_1"
            style="@style/HeaderTextStyle"
            android:layout_marginTop="@dimen/dimension_1"
            android:text="@string/text_1" />

        <RadioGroup
            android:id="@+id/radioGroup_1"
            style="@style/HeaderTextStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">


            <RadioButton
                android:id="@+id/radioButton_1a"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dimension_1"
                android:paddingLeft="@dimen/dimension_4"
                android:paddingRight="@dimen/dimension_5"
                android:text="@string/text_1a"
                android:textSize="@dimen/text_size_1" />

            <RadioButton
                android:id="@+id/radioButton_1b"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dimension_1"
                android:paddingLeft="@dimen/dimension_4"
                android:paddingRight="@dimen/dimension_5"
                android:text="@string/text_1b"
                android:textSize="@dimen/text_size_1" />

            <RadioButton
                android:id="@+id/radioButton_1c"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dimension_1"
                android:paddingLeft="@dimen/dimension_4"
                android:paddingRight="@dimen/dimension_5"
                android:text="@string/text_1c"
                android:textSize="@dimen/text_size_1" />

        </RadioGroup>

        <View
            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:layout_marginTop="25dp"
            android:background="#c0c0c0" />

        <TextView
            android:id="@+id/label_text_view_2"
            style="@style/HeaderTextStyle"
            android:layout_marginTop="@dimen/dimension_1"
            android:text="@string/text_2" />



            <CheckBox
                android:id="@+id/checkBox_2a"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="@dimen/dimension_4"
                android:paddingRight="@dimen/dimension_5"
                android:text="@string/text_2a"
                android:textSize="@dimen/text_size_1" />

            <CheckBox
                android:id="@+id/checkBox_2b"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dimension_1"
                android:paddingLeft="@dimen/dimension_4"
                android:paddingRight="@dimen/dimension_5"
                android:text="@string/text_2b"
                android:textSize="@dimen/text_size_1" />

            <CheckBox
                android:id="@+id/checkBox_2c"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dimension_1"
                android:paddingLeft="@dimen/dimension_4"
                android:paddingRight="@dimen/dimension_5"
                android:text="@string/text_2c"
                android:textSize="@dimen/text_size_1" />



    </LinearLayout>


</ScrollView>

strings.xml

<resources>

    <string name="text_button_1">check answers</string>

    <string name="app_name">Quiz Test</string>
    <string name="text_person_name">Type student name here.</string>
    <string name="text_directions">Select ALL correct answers:</string>

    <string name="text_1">1) probability distribution</string>
    <string name="text_1a">1a) A smooth curve indicating the frequency distribution for a discontinuous random variable.</string>
    <string name="text_1b">1b) A discontinuous dot diagram showing the frequency distribution for a random variable.</string>
    <string name="text_1c">1c) A smooth curve indicating the frequency distribution for a continuous random variable.</string>


    <string name="text_2">2)    normal distribution</string>
    <string name="text_2a">2a)   A smooth double-peak bell-shaped curve symmetrical about the mean.</string>
    <string name="text_2b">2b)   A smooth single-peak curve </string>
    <string name="text_2c">3c)   A bell-shaped curve symmetrical about the mean. </string>

</resources>

person JavaMon    schedule 21.09.2016    source источник


Ответы (2)


Я обновил XML, чтобы дать возможность отмечать красным крестиком неправильные ответы:

файл: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="false"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="@dimen/dimension_1"
        android:orientation="vertical">


        <EditText
            android:id="@+id/name_textView_STUDENT"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/text_person_name"
            android:inputType="textPersonName" />

        <TextView
            android:id="@+id/textView_directions"
            style="@style/HeaderTextStyle"
            android:layout_marginTop="@dimen/dimension_1"
            android:text="@string/text_directions"
            android:textSize="20sp" />


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/dimension_1"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/incorrect_question_1"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_marginTop="@dimen/dimension_1"
                android:gravity="center"
                android:text="X"
                android:textColor="#ff0000"
                android:textSize="30dp"
                android:visibility="gone" />

            <TextView
                android:id="@+id/textView_1"
                style="@style/HeaderTextStyle"
                android:layout_marginTop="@dimen/dimension_1"
                android:text="@string/text_1" />
        </LinearLayout>


        <RadioGroup
            android:id="@+id/radioGroup_1"
            style="@style/HeaderTextStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">


            <RadioButton
                android:id="@+id/radioButton_1a"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dimension_1"
                android:paddingLeft="@dimen/dimension_4"
                android:paddingRight="@dimen/dimension_5"
                android:textSize="@dimen/text_size_1"
                android:text="@string/text_1a"
                android:onClick="onClick_1a"/>


            <RadioButton
                android:id="@+id/radioButton_1b"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dimension_1"
                android:paddingLeft="@dimen/dimension_4"
                android:paddingRight="@dimen/dimension_5"
                android:text="@string/text_1b"
                android:textSize="@dimen/text_size_1"
                android:onClick="onClick_2a"/>/>

            <RadioButton
                android:id="@+id/radioButton_1c"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dimension_1"
                android:paddingLeft="@dimen/dimension_4"
                android:paddingRight="@dimen/dimension_5"
                android:text="@string/text_1c"
                android:textSize="@dimen/text_size_1"
                android:onClick="onClick_3a"/>

        </RadioGroup>

И разработал логику оценки Java для радиогрупп и флажков:

файл: MainActivity.java

package com.example.android.quiztest2;

/**
 * *Below added my unique package name "com.example.android.justjava4"
 */

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;


/**
 * package com.example.android.justjava4;
 * This app displays an order form to order coffee, and displays the information.
 * quantity is a global variable
 **/
public class MainActivity extends AppCompatActivity {
    private RadioButton radioButton_1a, radioButton_1b, radioButton_1c, radioButton_4a, radioButton_4b, radioButton_4c,
            radioButton_5a, radioButton_5b, radioButton_5c, radioButton_6a, RadioButton_6b, radioButton_6c,
            radioButton_7a, radioButton_7b, radioButton_7c, radioButton_9a, radioButton_9b, radioButton_9c;

    private CheckBox checkBox_2a, checkBox_2b, checkBox_2c, checkBox_3a, checkBox_3b, checkBox_3c, checkBox_8a, checkBox_8b, checkBox_8c;

    int grade = 0;

    public void Score(int grade) {
        if (radioButton_1c.isChecked())  grade++;

        if (radioButton_4c.isChecked())  grade++;

        if (radioButton_5c.isChecked()) grade++;

        if (radioButton_6c.isChecked()) grade++;

        if (radioButton_7c.isChecked()) grade++;

        if (radioButton_9c.isChecked()) grade++;

        if (checkBox_2a.isChecked() && !checkBox_2b.isChecked() && checkBox_2c.isChecked()) grade++;

        if (checkBox_3a.isChecked() && checkBox_3b.isChecked() && checkBox_3c.isChecked()) grade++;

        if (checkBox_8a.isChecked() && !checkBox_8b.isChecked() && checkBox_8c.isChecked()) grade++;

    }


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


        final Context currentContext = this;
        Button button_grade_quiz = (Button)
                findViewById(R.id.button_grade_quiz);
        button_grade_quiz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {



                boolean answerCorrect1 = false;

                TextView incorrectQuestionOne = (TextView) findViewById(R.id.incorrect_question_1);

                if (!answerCorrect1) {

                    incorrectQuestionOne.setVisibility(View.VISIBLE);
                } else {

                    incorrectQuestionOne.setVisibility(View.GONE);

                }

            }
        });
    }
}

Не уверен, как подключить функцию оценки к другим методам Java.

person JavaMon    schedule 24.09.2016

Простой ответ: добавьте кнопку в свой xml и назначьте ей идентификатор. Например, xml, скорее всего, будет выглядеть примерно так:

    <Button
        android:id="@+id/quiz_complete_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Finish Quiz"
        android:textSize="@dimen/text_size_1"
        android:layout_gravity="center"/>

Затем в MainActivity ПОСЛЕ вызова setContentView вы найдете представление кнопки по его идентификатору и установите для него onClickListener. Мой пример кода ниже включает грубый тест, который покажет сообщение Toast при нажатии кнопки, чтобы вы могли видеть, что кнопка правильно подключена к слушателю.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Context currentContext = this;
    Button quizAnsweredButton = (Button) findViewById(R.id.quiz_complete_button);
    quizAnsweredButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //do something
            Toast.makeText(currentContext, "TESTING", Toast.LENGTH_LONG).show();
        }
    });
}

(Примечание - чтобы уточнить, жирный шрифт выше означает, что вы можете ссылаться на представления только после того, как они отображаются - это то, что делается с помощью setContentView выше. Если вы попытаетесь вызвать findViewById до setContentView, вы получите сбой.)

Здесь все становится сложнее. Без написания всего решения для достижения вашей цели я бы добавил все, что вы хотели бы, чтобы викторина выглядела, если пользователь отправит тест со всеми неправильными ответами, в xml. Я создал xml для вопроса 1. (Я добавил горизонтальный LinearLayout, чтобы сохранить остальную часть вашего xml, но из-за сложности вашего представления я бы рекомендовал использовать RelativeLayout) Как видите, видимость неправильный ярлык установлен на "ушел". Это означает, что представление не будет отображаться, но также не будет занимать место с родительским представлением. «невидимый» скроет вид, но его пространство все равно будет заполнено.

Теперь, когда тест будет отправлен, мы покажем этикетку с неверным ответом. В своем полном решении вы, конечно же, оцените, правильный ответ или нет.

XML для метки первого вопроса:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/question_1_incorrect_label"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:textColor="@color/red"
            android:gravity="center"
            android:visibility="gone"/>
        <TextView
            android:id="@+id/label_text_view_1"
            style="@style/HeaderTextStyle"
            android:layout_marginTop="@dimen/dimension_1"
            android:text="@string/text_1" />
    </LinearLayout>

Обновлено MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Context currentContext = this;
    Button quizAnsweredButton = (Button) findViewById(R.id.quiz_complete_button);
    quizAnsweredButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean answer1Correct = false;
            //TODO: Evaluate the actual value of answer1Correct boolean.
            TextView questionOneIncorrectLabel = (TextView)findViewById(R.id.question_1_incorrect_label);
            if (!answer1Correct) {
                questionOneIncorrectLabel.setVisibility(View.VISIBLE);
            }
            else {
                questionOneIncorrectLabel.setVisibility(View.GONE);
            }
        }
    });
}

Примечание - в colors.xml добавлено:

<color name="red">#FF0000</color

Остальное - это просто работа, чтобы заставить его работать, а также код в MainActivity для анализа правильности каждого ответа.

Наконец, подсказка для упрощения вашего правильного ответного сообщения. Вы можете создать строковую константу с заполнителем для значения, которое будет добавлено позже. Например:

<string name="text_quiz_complete_answers">You answered %d question(s) correctly.</string>

При извлечении этого строкового значения из файла strings.xml вы ссылаетесь на него следующим образом:

String.format(getString(R.string.text_quiz_complete_answers), 5)

С 5 просто заполнителем. Вместо этого должно быть вычисленное вами числовое значение.

Для получения дополнительной информации о форматировании таких строк я бы сослался на этот пост: Параметры в строках. xml можно?

person Matt Shaw    schedule 21.09.2016