android - 如何从数组列表中隐藏 2 个不正确的答案并启用 2 个可能的答案?

标签 android button

我有 4 个按钮,每次单击帮助按钮时,我想从列表中隐藏 2 个错误答案。我的问题是如何启用具体答案?所有以为我知道正确的但是当我点击帮助按钮时正确的答案也被选择隐藏。如何设置正确的答案来显示和随机隐藏2个错误的答案?我用了 button.setVisibility(View.VISIBLE);button.setVisibility(View.INVISIBLE); 隐藏和显示 按钮

下面是我的代码。

public class QuestionActivity extends Activity {

MediaPlayer mySound;
List<Question> quesList;
int qid = 0;

//for help 50/50
int help =0;
int score = 0;
int rnd2 ,rnd1;

ProgressBar progressBar;
private static  MyCountDownTimer myCountDownTimer;
// Animation
Animation animFadein;
Question currentQ;
TextView txtQuestion, scored;
Button button1, button2, button3, button4,helpbtn;
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;


public void help (View view){
    helpbtn=(Button)findViewById(R.id.helpbtn);
    helpbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            v.setEnabled(false);
            help = help -1;

            if(help == 0){
                helpbtn.setEnabled(false);

            }
            if (help > 0){
                helpbtn.setEnabled(true);

            }

            String AnswerString = currentQ.getANSWER();
            //match DB answer to selected answer, turn it visible if it is correct
            if(button1.getText().equals(AnswerString)){
                button1.setVisibility(View.VISIBLE);
            }
            if(button2.getText().equals(AnswerString)){
                button2.setVisibility(View.VISIBLE);
            }
            if(button3.getText().equals(AnswerString)){
                button3.setVisibility(View.VISIBLE);
            }
            if(button4.getText().equals(AnswerString)){
                button4.setVisibility(View.VISIBLE);
            }
            //random hide 2 incorrect answers
            List<Integer> list = Arrays.asList(1, 2, 3, 4);
            Collections.shuffle(list);
            rnd1 = list.get(0);
            rnd2 = list.get(1);

            /*int answer = 2; // Correct answer
            List<Integer> list = new ArrayList<>();
            rnd1 = list.get(0);
            rnd2 = list.get(1);
            for(int i = 1; i<= 4 ; i++) {
                if (i != answer) {
                    list.add(i);
                }
            }*/

            if ((rnd1 == 1) || (rnd2 == 1)){
                button1.getText().equals(AnswerString);
                button1.setVisibility(View.INVISIBLE);
            }
            if ((rnd1 == 2) || (rnd2 == 2)){
                button2.getText().equals(AnswerString);
                button2.setVisibility(View.INVISIBLE);
            }
            if ((rnd1 == 3) || (rnd2 == 3)){
                button3.getText().equals(AnswerString);
                button3.setVisibility(View.INVISIBLE);
            }
            if ((rnd1 == 4) || (rnd2 == 4)){
                button4.getText().equals(AnswerString);
                button4.setVisibility(View.INVISIBLE);
            }
        }
    });
}
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_qestion);
    QuizHelper db = new QuizHelper(this);  // my question bank class
    quesList = db.getAllQuestions();  // this will fetch all questions
    currentQ = quesList.get(qid); // the current question
    mySound = MediaPlayer.create(this, R.raw.bensoundcute); // music background
    mySound.start();
    mySound.setLooping(true);
    mySound.setAudioStreamType(AudioManager.STREAM_MUSIC);
    txtQuestion = (TextView) findViewById(R.id.txtQuestion);
    // load the textQuestion animation
    animFadein = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in);
    // the text view in which the question will be displayed
    // the 4 buttons,
    // the idea is to set the text of 4 buttons with the options from question bank
    progressBar = (ProgressBar)findViewById(R.id.progressbar);
    button1 = (Button) findViewById(R.id.button1);
    button2 = (Button) findViewById(R.id.button2);
    button3 = (Button) findViewById(R.id.button3);
    button4 = (Button) findViewById(R.id.button4);
    // the text view in which score will be displayed
    scored = (TextView) findViewById(R.id.score);
    // method which will set the things up for our game
    setQuestionView(false);
    txtQuestion.setAnimation(animFadein);
    txtQuestion.startAnimation(animFadein);


    // button click listeners
    final MediaPlayer buttonSound = MediaPlayer.create(this, R.raw.play);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            buttonSound.start();
            // passing the button text to other method
            // to check whether the answer is correct or not
            // same for all three buttons
            getAnswer(button1.getText().toString());
            if(myCountDownTimer != null) {
                myCountDownTimer.cancel(); // Stop Timer
            }
            progressBar.setProgress(100);
            myCountDownTimer = new MyCountDownTimer(30000, 500);
            myCountDownTimer.start();


        }
    });
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            buttonSound.start();
            getAnswer(button2.getText().toString());
            if(myCountDownTimer != null) {
                myCountDownTimer.cancel(); // Stop Timer
            }
            progressBar.setProgress(100);
            myCountDownTimer = new MyCountDownTimer(30000, 500);
            myCountDownTimer.start();

        }
    });
    button3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            buttonSound.start();
            getAnswer(button3.getText().toString());
            if(myCountDownTimer != null) {
                myCountDownTimer.cancel(); // Stop Timer
            }
            progressBar.setProgress(100);
            myCountDownTimer = new MyCountDownTimer(30000, 500);
            myCountDownTimer.start();

        }
    });
    button4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            buttonSound.start();
            getAnswer(button4.getText().toString());
            if(myCountDownTimer != null) {
                myCountDownTimer.cancel(); // Stop Timer
            }
            progressBar.setProgress(100);
            myCountDownTimer = new MyCountDownTimer(30000, 500);
            myCountDownTimer.start();
        }
    });
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

    // Create custom dialog object

    final Dialog dialog = new Dialog(QuestionActivity.this ,android.R.style.Theme_NoTitleBar_Fullscreen);

    // Include dialog.xml file
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.dialog);


    // Set dialog title
    // set values for custom dialog components - text, image and button
    TextView text = (TextView) dialog.findViewById(R.id.textDialog);
    text.setText("Everytime you get 5 Correct answer, youre help points increases, use this help points to elemenate 2 incorrect answer");
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.getWindow().setLayout(WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.MATCH_PARENT);

    dialog.show();
    Button declineButton = (Button) dialog.findViewById(R.id.declineButton);
    // if decline button is clicked, close the custom dialog
    declineButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Close dialog
            dialog.cancel();
            buttonSound.start();

            if(myCountDownTimer != null) {
                myCountDownTimer.cancel(); // Stop Timer
            }
            progressBar.setProgress(100);
            myCountDownTimer = new MyCountDownTimer(30000, 500);
            myCountDownTimer.start();

        }
    });
}
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
public Action getIndexApiAction() {
    Thing object = new Thing.Builder()
            .setName("Question Page") // TODO: Define a title for the content shown.
            // TODO: Make sure this auto-generated URL is correct.
            .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
            .build();
    return new Action.Builder(Action.TYPE_VIEW)
            .setObject(object)
            .setActionStatus(Action.STATUS_TYPE_COMPLETED)
            .build();
}

@Override
public void onStart() {
    super.onStart();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client.connect();
    AppIndex.AppIndexApi.start(client, getIndexApiAction());
}

@Override
public void onStop() {
    super.onStop();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    AppIndex.AppIndexApi.end(client, getIndexApiAction());
    client.disconnect();
    myCountDownTimer.cancel();
}

public class MyCountDownTimer extends CountDownTimer {
    public MyCountDownTimer(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }
    @Override
    public void onTick(long millisUntilFinished) {
        int progress = (int) (millisUntilFinished/300);
        Log.v("Log_tag", "Timer Progress "  + millisUntilFinished);
        progressBar.setProgress(progress);
    }
    @Override
    public void onFinish() {
        if(myCountDownTimer != null) {
            myCountDownTimer.cancel(); // Stop Timer
        }
        progressBar.setProgress(0);
        myCountDownTimer.cancel();
        Toast.makeText(getApplicationContext(),
                "Times Up!.",
                Toast.LENGTH_SHORT)
                .show();
        if (score > 49){
            Intent intent = new Intent(QuestionActivity.this,
                    Successresult.class);
            // passing the int value
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            setQuestionView(false);
            myCountDownTimer.cancel();
            startActivity(intent);
            finish();
        } else {
            Intent intent = new Intent(QuestionActivity.this,
                    ResultActivity.class);
            // passing the int value
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            setQuestionView(false);
            startActivity(intent);
            myCountDownTimer.cancel();
            finish();
        }
    }



}
@Override
protected void onPause(){
    super.onPause();
    mySound.release();
    finish();
}
@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(false);
    builder.setMessage("Do you want to Exit?");
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //if user pressed "yes", then he is allowed to exit from application
            dialog.dismiss();
            onYesClick();
        }
        private void onYesClick() {
            Intent setIntent = new Intent(Intent.ACTION_MAIN);
            setIntent.addCategory(Intent.CATEGORY_HOME);
            setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(setIntent);
            myCountDownTimer.cancel();
            finish();
            QuestionActivity.this.finish();
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //if user select "No", just cancel this dialog and continue with app
            dialog.cancel();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}
public void getAnswer(String AnswerString) {
    myCountDownTimer.cancel();
    Log.d("TIMER", "timer canceled");
    Log.d("Tag", "score = " + score + ", help = " + help +" remaining");
    if(myCountDownTimer != null) {
        myCountDownTimer.cancel(); // Stop Timer
    }

    if (currentQ.getANSWER().equals(AnswerString)) {
        // if conditions matches increase the int (score) by 1
        // and set the text of the score view

        Toast.makeText(getApplicationContext(), "CORRECT!", Toast.LENGTH_SHORT).show();
        score++;
        scored.setText("Score:  " + score + " /100");
        if(score % 5 == 0) {
            help = help+1;
            Log.d("Tag", "score = " + score + ", help = " + help);
            Toast.makeText(getApplicationContext(), "Your help Encreases", Toast.LENGTH_SHORT).show();
        }
    }
    else {
        Log.d("TIMER", "timer canceled");
        myCountDownTimer.cancel();
        // if unlucky start activity and finish the game
        Toast.makeText(getApplicationContext(), "Sorry! Better luck next time.", Toast.LENGTH_SHORT).show();
        if (score > 49){
            myCountDownTimer.cancel();
            Intent intent = new Intent(QuestionActivity.this,
                    Successresult.class);
            // passing the int value
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            setQuestionView(false);
            startActivity(intent);
            finish();
        } else {
            Intent intent = new Intent(QuestionActivity.this,
                    ResultActivity.class);
            // passing the int value
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            setQuestionView(false);
            myCountDownTimer.cancel();
            startActivity(intent);
            finish();
        }
    }
    if(qid < 101) {
        // if questions are not over then do this
        currentQ = quesList.get(qid);
        setQuestionView(true);
        txtQuestion.setAnimation(animFadein);
        txtQuestion.startAnimation(animFadein);
        button1 .setVisibility(View.VISIBLE);
        button2 .setVisibility(View.VISIBLE);
        button3 .setVisibility(View.VISIBLE);
        button4 .setVisibility(View.VISIBLE);
    }
    else {
        myCountDownTimer.cancel();
        // if unlucky start activity and finish the game
        Toast.makeText(getApplicationContext(), "Game Over.", Toast.LENGTH_SHORT).show();
        if (score > 49){
            Intent intent = new Intent(QuestionActivity.this,
                    Successresult.class);
            // passing the int value
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            setQuestionView(false);
            startActivity(intent);
            finish();
        } else {
            Intent intent = new Intent(QuestionActivity.this,
                    ResultActivity.class);
            // passing the int value
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            setQuestionView(false);
            startActivity(intent);
            finish();
        }
    }
}
private boolean setQuestionView(boolean b) {
    // the method which will put all things together

    txtQuestion.setText(currentQ.getQUESTION());
    button1.setText(currentQ.getOPTA());
    button2.setText(currentQ.getOPTB());
    button3.setText(currentQ.getOPTC());
    button4.setText(currentQ.getOPTD());

    qid++;
    return b;
}

最佳答案

在此列表中不要添加正确答案的数字, List list = Arrays.asList(1, 2, 3, 4);

即:如果正确答案为 2,则将列表设置如下

        int answer = 2; // Correct answer
        List<Integer> list = new ArrayList<>();
        for(int i = 1; i<= 4 ; i++) {
            if(i != answer) {
                list.add(i);
            }
        }

所以当你得到随机数时,答案按钮不会被隐藏

关于android - 如何从数组列表中隐藏 2 个不正确的答案并启用 2 个可能的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41057972/

相关文章:

java - 如何使用 View 的子级制作绘图动画,逐个绘制每个 Path 的线?

css - 基于图像的按钮在 IE9 中模糊

android - 即时应用程序基础功能的 Application.onCreate() 从未调用过

ios - 在 SwiftUI 中按下按钮时如何检测并采取措施

android - 看中 Android 菜单按钮布局

JavaScript 事件监听器未添加到按钮

python - 如何使用 python 同时按下多个 tkinter 按钮

java - 无法理解数据更改通知如何与 Android 中的 Firestore 配合使用。谁能解释一下吗?

c# - Java 格式 Date to UTC 有时会产生 '????-??-??T??:??:??.???Z'

java - Android 按钮导航与 onclick 监听器