如果答案是错误的android怎么能显示正确的答案?

时间:2017-10-02 09:03:08

标签: java android

CheckAns 中,如果来自数据或网络API的答案是正确的,那么我想知道答案是否正确无法显示正确的答案。

所以这里的想法在回答问题后会显示当前点级别的级别对话框,所以我想在错误时显示正确的答案 当答案是正确时,应用程序继续下一个问题,但如果错误,应用程序显示当前点对话框。

enter image description here

package com.app.trafficexam;


import android.content.ContentValues;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.db.DatabaseHelper;
import com.example.item.ItemStage;
import com.example.util.Constant;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

public class PlayQuizActivity extends AppCompatActivity {

    WebView web_desc;
    private long timeCountInMilliSeconds = (long) (0.50 * 60000);

    private enum TimerStatus {
        STARTED,
        STOPPED
    }

    private TimerStatus timerStatus = TimerStatus.STOPPED;
    private ProgressBar progressBarCircle;
    private TextView textViewTime, txt_pointshow;
    private CountDownTimer countDownTimer;
    Button btnopta, btnoptb, btnoptc, btnoptd;
    String str_a, str_b, str_c, str_d, ansright;
    private int currentPosition;
    int TOTAL_TEXT, points, time;
    ArrayList<ItemStage> mListItem;
    boolean isTimerOn;
    long millisTimerRemains;
    DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playquiz_activity);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
        }
        setTitle(getString(R.string.app_name));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        AdView mAdView = (AdView) findViewById(R.id.adView);
        mAdView.loadAd(new AdRequest.Builder().build());

        mListItem = new ArrayList<>();
        web_desc = (WebView) findViewById(R.id.text_question);
        progressBarCircle = (ProgressBar) findViewById(R.id.progressBarCircle);
        textViewTime = (TextView) findViewById(R.id.textViewTime);
        txt_pointshow = (TextView) findViewById(R.id.text_point);
        btnopta = (Button) findViewById(R.id.btn_optionA);
        btnoptb = (Button) findViewById(R.id.btn_optionB);
        btnoptc = (Button) findViewById(R.id.btn_optionC);
        btnoptd = (Button) findViewById(R.id.btn_optionD);
        databaseHelper = new DatabaseHelper(getApplicationContext());

        web_desc.setBackgroundColor(0);
        web_desc.setFocusableInTouchMode(false);
        web_desc.setFocusable(false);
        web_desc.getSettings().setDefaultTextEncodingName("UTF-8");
        web_desc.getSettings().setDefaultFontSize(18);
        isTimerOn = false;

        Intent i = getIntent();
        currentPosition = i.getIntExtra("POSITION", 0);

        TOTAL_TEXT = Constant.arrayList.size() - 1;

        setQuestionView(currentPosition);

        btnopta.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                str_a = Constant.arrayList.get(currentPosition).getLevelWiseQuesOptA();
                CheckAns();

            }
        });

        btnoptb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                str_b = Constant.arrayList.get(currentPosition).getLevelWiseQuesOptB();
                CheckAns();

            }
        });

        btnoptc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                str_c = Constant.arrayList.get(currentPosition).getLevelWiseQuesOptC();
                CheckAns();

            }
        });

        btnoptd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                str_d = Constant.arrayList.get(currentPosition).getLevelWiseQuesOptD();
                CheckAns();

            }
        });
    }

    public void CheckAns() {
        ansright = Constant.arrayList.get(currentPosition).getLevelWiseQuesAns();
        if (ansright.equals(str_a)) {
            isAnswerTrue();
            startStop();
        } else if (ansright.equals(str_b)) {
            isAnswerTrue();
            startStop();
        } else if (ansright.equals(str_c)) {
            isAnswerTrue();
            startStop();
        } else if (ansright.equals(str_d)) {
            isAnswerTrue();
            startStop();
        } else {
            Intent intentres = new Intent(PlayQuizActivity.this, ResultActivity.class);
            intentres.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intentres);
            stopCountDownTimer();
        }
    }

    private void isAnswerTrue() {

        if (currentPosition <= TOTAL_TEXT) {

            time = (int) millisTimerRemains;
            int point = PointCount(time);

            if (!databaseHelper.getFavouriteById(Constant.arrayList.get(currentPosition).getLevelWiseQuesId())) {
                ContentValues fav = new ContentValues();
                fav.put(DatabaseHelper.KEY_LEVEL_ID, Constant.arrayList.get(currentPosition).getLevelWiseQuesLevelId());
                fav.put(DatabaseHelper.KEY_STAGE_ID, Constant.arrayList.get(currentPosition).getLevelWiseQuesId());
                fav.put(DatabaseHelper.KEY_TOTAL_POINT, point);
                databaseHelper.addFavourite(DatabaseHelper.TABLE_FAVOURITE_NAME, fav, null);
            }
            if (currentPosition < TOTAL_TEXT) {
                if (!databaseHelper.getFavouriteById(Constant.arrayList.get(currentPosition).getLevelWiseQuesId())) {
                    ContentValues fav = new ContentValues();
                    fav.put(DatabaseHelper.KEY_LEVEL_ID, Constant.arrayList.get(currentPosition).getLevelWiseQuesLevelId());
                    fav.put(DatabaseHelper.KEY_STAGE_ID, Constant.arrayList.get(currentPosition).getLevelWiseQuesId());
                    fav.put(DatabaseHelper.KEY_TOTAL_POINT, point);
                    databaseHelper.addFavourite(DatabaseHelper.TABLE_FAVOURITE_NAME, fav, null);
                }
                setQuestionView(currentPosition + 1);
            }
            else{
                Intent intentres = new Intent(PlayQuizActivity.this, ResultActivity.class);
                intentres.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intentres);
                stopCountDownTimer();
            }

        } else {
            Intent intentres = new Intent(PlayQuizActivity.this, ResultActivity.class);
            intentres.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intentres);
            stopCountDownTimer();
        }
    }

    private void setQuestionView(int positionToMoveTo) {
        String mimeType = "text/html";
        String encoding = "utf-8";
        String htmlText = Constant.arrayList.get(positionToMoveTo).getLevelWiseQuesQuestion();

        String text = "<html><head>"
                + "<style type=\"text/css\">@font-face {font-family: MyFont;src: url(\"file:///android_asset/fonts/custom.ttf\")}body{font-family: MyFont;color: #ffffff;text-align:justify}"
                + "</style></head>"
                + "<body>"
                + htmlText
                + "</body></html>";

        web_desc.loadDataWithBaseURL(null, text, mimeType, encoding, null);
        btnopta.setText(Constant.arrayList.get(positionToMoveTo).getLevelWiseQuesOptA());
        btnoptb.setText(Constant.arrayList.get(positionToMoveTo).getLevelWiseQuesOptB());
        btnoptc.setText(Constant.arrayList.get(positionToMoveTo).getLevelWiseQuesOptC());
        btnoptd.setText(Constant.arrayList.get(positionToMoveTo).getLevelWiseQuesOptD());
        currentPosition = positionToMoveTo;
        startStop();

    }

    public int PointCount(int timeremain) {
        if (timeremain < 29 && timeremain >= 25) {
            points = 5;
            txt_pointshow.setText("" + points);
        } else if (timeremain < 25 && timeremain >= 20) {
            points = 3;
            txt_pointshow.setText("" + points);
        } else if (timeremain < 20 && timeremain >= 1) {
            points = 1;
            txt_pointshow.setText("" + points);
        }

        return points;
    }

    private void startStop() {
        if (timerStatus == TimerStatus.STOPPED) {
            setProgressBarValues();
            timerStatus = TimerStatus.STARTED;
            startCountDownTimer();

        } else {

            timerStatus = TimerStatus.STOPPED;
            stopCountDownTimer();

        }
    }

    private void startCountDownTimer() {

        countDownTimer = new CountDownTimer(timeCountInMilliSeconds, 1000) {
            @Override
            public void onTick(final long millisUntilFinished) {

                textViewTime.setText(hmsTimeFormatter(millisUntilFinished));
                progressBarCircle.setProgress((int) (millisUntilFinished / 1000));
                millisTimerRemains = (millisUntilFinished / 1000);

            }

            @Override
            public void onFinish() {

                textViewTime.setText(hmsTimeFormatter(timeCountInMilliSeconds));
                setProgressBarValues();
                timerStatus = TimerStatus.STOPPED;
                //finish();
                Intent intentres = new Intent(PlayQuizActivity.this, ResultActivity.class);
                intentres.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intentres);

            }

        }.start();
        countDownTimer.start();
    }

    private void stopCountDownTimer() {
        countDownTimer.cancel();
    }

    private void setProgressBarValues() {

        progressBarCircle.setMax((int) timeCountInMilliSeconds / 1000);
        progressBarCircle.setProgress((int) timeCountInMilliSeconds / 1000);
    }

    private String hmsTimeFormatter(long milliSeconds) {
        String hms = String.format("%02d",
                TimeUnit.MILLISECONDS.toSeconds(milliSeconds) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliSeconds)));

        return hms;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;

            default:
                return super.onOptionsItemSelected(menuItem);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopCountDownTimer();
    }
}

1 个答案:

答案 0 :(得分:0)

我建议如果用户点击错误答案的按钮,只需更改按钮的背景颜色,正确的答案为绿色,错误的答案为红色,然后有一个文本视图,显示所选的答案和正确的答案,如果用户选择了正确的答案,那么只需显示下一个问题:

sample screen

<强>更新

好的,我创建了一个我正在谈论的简单例子。

首先,您必须创建三个drawable(在res-&gt; drawable中),它们将是按钮的背景:

  • button.xml - &gt;灰色(默认背景)
  • background button_wrong.xml - &gt;阅读背景
  • button_correct.xml - &gt;绿色背景

<强> button.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true">
    <shape android:shape="rectangle">
      <corners android:radius="3dp" />
      <solid android:color="#807676"/>
    </shape>
  </item>
  <item android:state_focused="true">
    <shape android:shape="rectangle">
      <corners android:radius="3dp" />
      <solid android:color="#BCBCBC" />
    </shape>
  </item>
  <item android:state_enabled="false">
    <shape android:shape="rectangle">
      <corners android:radius="3dp" />
      <solid android:color="#807676" />
    </shape>
  </item>
  <item>
    <shape android:shape="rectangle">
      <corners android:radius="3dp" />
      <solid android:color="#BCBCBC" />
    </shape>
  </item>
</selector>

<强> button_wrong.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true">
    <shape android:shape="rectangle">
      <corners android:radius="3dp" />
      <solid android:color="#f46767"/>
    </shape>
  </item>
  <item android:state_focused="true">
    <shape android:shape="rectangle">
      <corners android:radius="3dp" />
      <solid android:color="#ff4040" />
    </shape>
  </item>
  <item android:state_enabled="false">
    <shape android:shape="rectangle">
      <corners android:radius="3dp" />
      <solid android:color="#86ff4040" />
    </shape>
  </item>
  <item>
    <shape android:shape="rectangle">
      <corners android:radius="3dp" />
      <solid android:color="#ff4040" />
    </shape>
  </item>
</selector>

<强> button_correct.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true">
    <shape android:shape="rectangle">
      <corners android:radius="3dp" />
      <solid android:color="#67f47c"/>
    </shape>
  </item>
  <item android:state_focused="true">
    <shape android:shape="rectangle">
      <corners android:radius="3dp" />
      <solid android:color="#40FF5D" />
    </shape>
  </item>
  <item android:state_enabled="false">
    <shape android:shape="rectangle">
      <corners android:radius="3dp" />
      <solid android:color="#8640ff5d" />
    </shape>
  </item>
  <item>
    <shape android:shape="rectangle">
      <corners android:radius="3dp" />
      <solid android:color="#40FF5D" />
    </shape>
  </item>
</selector>

其次,使用布局上的drawable(button.xml)作为默认按钮背景:

<强> activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp"
    tools:context="ph.codehood.myapplication.MainActivity">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:padding="20dp"
        android:text="-- Result will appear here --"
        android:textAlignment="center" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/button"
        android:text="SELECTION ITEM" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/button"
        android:text="SELECTION ITEM" />

    <Button
        android:id="@+id/btn3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/button"
        android:text="SELECTION ITEM" />

    <Button
        android:id="@+id/btn4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/button"
        android:text="SELECTION ITEM" />

</LinearLayout>

然后最后,实现代码:

<强> MainActivity.java

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    String correctAnswer = "C"; // <= Define the correct answer A, B, C, or D
    Button correctButton;
    TextView textView1;

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

        Button btn1 = (Button) findViewById(R.id.btn1);
        Button btn2 = (Button) findViewById(R.id.btn2);
        Button btn3 = (Button) findViewById(R.id.btn3);
        Button btn4 = (Button) findViewById(R.id.btn4);

        // Define which button has the correct answer
        switch (correctAnswer) {
            case "A":
                correctButton = btn1;
                break;
            case "B":
                correctButton = btn2;
                break;
            case "C":
                correctButton = btn3;
                break;
            case "D":
                correctButton = btn4;
                break;
        }

        correctButton.setText("CORRECT ANSWER");

        textView1 = (TextView) findViewById(R.id.textView1);


        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAnswer("A", v);
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAnswer("B", v);
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAnswer("C", v);
            }
        });

        btn4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAnswer("D", v);
            }
        });

    }

    void checkAnswer(String selectionLetter, View v) {

        // change background of correct answer to green
        correctButton.setBackgroundResource(R.drawable.button_correct);

        if (selectionLetter.equals(correctAnswer)) {
            textView1.setText("-- Correct Answer, Proceed to next question -- ");
        } else {
            // change background of correct answer to red
            textView1.setText("WRONG ANSWER\nCORRECT IS: " + correctAnswer + "\nSELECTED: " + selectionLetter);
            v.setBackgroundResource(R.drawable.button_wrong);
        }

        resetBackgrounds(v);
    }

    void resetBackgrounds(final View v) {
        // Reset everything after 1.5 sec
        Runnable runnable = new Runnable() {
            public void run() {
                textView1.setText("-- Result will appear here --");
                v.setBackgroundResource(R.drawable.button);
                correctButton.setBackgroundResource(R.drawable.button);
            }
        };

        Handler handler = new android.os.Handler();
        handler.postDelayed(runnable, 1500);
    }
}

在单独的Android Studio项目上测试此代码以查看输出。

enter image description here