Как добавить таймер в этот тест для Android?

#java #android #android-fragments #timer #countdowntimer

#java #Android #android-фрагменты #таймер #таймер обратного отсчета

Вопрос:

Я разрабатываю программу викторины, в которой вопросы отображаются фрагментами.

  • Для истинных / ложных вопросов 1-й фрагмент
  • Для 2-го фрагмента MCQ
  • MainActivity (из main я отправляю список qs во фрагмент mcq и еще один)

Эти 2 фрагмента отображаются случайным образом, пока тест закончен. Но мне нужно добавить таймер к каждому фрагменту. Как я могу этого добиться?

Я опубликовал фрагмент кода MCQ, другой такой же, как этот. (отличаются только интерфейсы) Я хочу знать, куда именно мне нужно поместить таймер в этом.

ActivityMCQ.java (MCQ — фрагмент)

 public class ActivityMCQ extends Fragment implements View.OnClickListener {

    private ImageView iv_yellow_bin, iv_red_bin, iv_black_bin, iv_blue_sharp_box, iv_white_sharp_box, iv_question_image;
    private TextView tv_name_of_image;

    private int current_questionMCQ,current_questionTrueFalse;
    private int score;
    private ArrayList<Question> mSQSList =  new ArrayList<>();
    private ArrayList<Question> trueFalseQsList =  new ArrayList<>();
    private boolean isFirstMCQ,isFirstTrueFalse;
    private static final int TOTAL_NO_OF_QS = 13;
    private TextView timer;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.activity_mcq, container, false);
        tv_name_of_image = root.findViewById(R.id.tv_name_of_image);
        iv_yellow_bin = root.findViewById(R.id.iv_yellow_bin);
        iv_red_bin = root.findViewById(R.id.iv_red_bin);
        iv_black_bin = root.findViewById(R.id.iv_black_bin);
        iv_blue_sharp_box = root.findViewById(R.id.iv_blue_sharp_box);
        iv_white_sharp_box = root.findViewById(R.id.iv_white_sharp_box);
        timer = root.findViewById(R.id.timer);
        iv_yellow_bin.setOnClickListener(this);
        iv_red_bin.setOnClickListener(this);
        iv_black_bin.setOnClickListener(this);
        iv_blue_sharp_box.setOnClickListener(this);
        iv_white_sharp_box.setOnClickListener(this);
        iv_question_image = root.findViewById(R.id.iv_question_image);


        trueFalseQsList = (ArrayList<Question>)getArguments().getSerializable("trueFalseQsList");
        mSQSList = (ArrayList<Question>)getArguments().getSerializable("mSQSList");
        current_questionMCQ = getArguments().getInt("current_questionMCQ");
        current_questionTrueFalse = getArguments().getInt("current_questionTrueFalse");
        score = getArguments().getInt("score");
        isFirstTrueFalse = getArguments().getBoolean("isFirstTrueFalse");
        isFirstMCQ = getArguments().getBoolean("isFirstMCQ");






        if(isFirstMCQ){
            iv_question_image.setImageDrawable(getResources().getDrawable(mSQSList.get(0).getImageId()));
            tv_name_of_image.setText(mSQSList.get(0).getQuestion());
            isFirstMCQ = false;

            new CountDownTimer(30000, 1000) {
                public void onTick(long millisUntilFinished) {
                    timer.setText("Seconds remaining: "   millisUntilFinished / 1000);
                }

                public void onFinish() {
                    move();
                }
            }.start();
        }else{
            moveToNextQuestion();


        }




        return root;
    }




    public void checkAnswer(String markedAnswer){

        if(mSQSList.get(current_questionMCQ).getColor().equals(markedAnswer)){
            score  ;
            showAnswerDetail(true);
        }else{
            showAnswerDetail(false);
        }

    }

    public void moveToNextQuestion(){
        Log.w("LOGs","CURRENT QS animateQuestion : " current_questionMCQ);

        if (current_questionMCQ current_questionTrueFalse<TOTAL_NO_OF_QS){
            new CountDownTimer(30000, 1000) {
                public void onTick(long millisUntilFinished) {
                    timer.setText("Seconds remaining: "   millisUntilFinished / 1000);
                }

                public void onFinish() {
                    animateQuestion(getActivity(), iv_question_image, BitmapFactory.decodeResource(getResources(), mSQSList.get(current_questionMCQ).getImageId()) , tv_name_of_image, mSQSList.get(current_questionMCQ).getQuestion());
                }
            }.start();
        }else {
            showDialogue();
        }
    }




    public void showDialogue(){
        androidx.appcompat.app.AlertDialog.Builder alertDialog2 = new androidx.appcompat.app.AlertDialog.Builder(getActivity());
        alertDialog2.setTitle("Finished!");
        final LinearLayout linearLayout = new LinearLayout(getActivity());
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        final TextView total_questions = new TextView(getActivity());
        LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        total_questions.setText("Your Score = "   score   "/5.");
        alertDialog2.setPositiveButton("Exit amp; Go to Dashboard",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        startActivity(new Intent(getActivity(), ActivityHomepage.class));
                    }
                });
        alertDialog2.setNegativeButton("Retry This Test",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        startActivity(new Intent(getActivity(), Quiz_Main.class));
                    }
                });
        total_questions.setPadding(100, 30,0,0);
        total_questions.setLayoutParams(lp2);
        linearLayout.addView(total_questions);
        alertDialog2.setView(linearLayout);
        alertDialog2.setCancelable(false);
        alertDialog2.show();
    }

    public static void animateQuestion(Context c, final ImageView iv_question, final Bitmap question_image, final TextView tv_question, final String question_text) {
        iv_question.setImageBitmap(question_image);
        tv_question.setText(question_text);

        /*final Animation anim_out = AnimationUtils.loadAnimation(c, android.R.anim.fade_out);
        final Animation anim_in  = AnimationUtils.loadAnimation(c, android.R.anim.fade_in);

        anim_out.setAnimationListener(new Animation.AnimationListener() {

            @Override public void onAnimationStart(Animation animation) {}
            @Override public void onAnimationRepeat(Animation animation) {}
            @Override public void onAnimationEnd(Animation animation)
            {
                iv_question.setImageBitmap(question_image);
                tv_question.setText(question_text);
                anim_in.setAnimationListener(new Animation.AnimationListener() {
                    @Override public void onAnimationStart(Animation animation) {}
                    @Override public void onAnimationRepeat(Animation animation) {}
                    @Override public void onAnimationEnd(Animation animation) {}
                });
                iv_question.startAnimation(anim_in);
                tv_question.startAnimation(anim_in);
            }
        });

        iv_question.startAnimation(anim_out);
        tv_question.startAnimation(anim_out);*/
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_yellow_bin:
                checkAnswer("Yellow");
                break;

            case R.id.iv_red_bin:
                checkAnswer("Red");
                break;

            case R.id.iv_black_bin:
                checkAnswer("Black");
                break;

            case R.id.iv_blue_sharp_box:
                checkAnswer("Blue");
                break;

            case R.id.iv_white_sharp_box:
                checkAnswer("White");
                break;
        }
    }

    public void showAnswerDetail(boolean isCorrect){
        AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(getActivity());
        alertDialog2.setTitle(isCorrect ? "Correct Answer!" : "Wrong Answer!");

        final LinearLayout linearLayout = new LinearLayout(getActivity());
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        final TextView total_questions = new TextView(getActivity());
        LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        total_questions.setText("Your Score = "   score   "/15.");
        alertDialog2.setPositiveButton("Next Question",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Log.w("LOGs","CURRENT TRUEFALS QS : " current_questionTrueFalse);
                        Log.w("LOGs","CURRENT MCQ QS : " current_questionMCQ);

                        move();
                    }
                });
        total_questions.setPadding(100, 30,0,0);
        total_questions.setLayoutParams(lp2);
        linearLayout.addView(total_questions);
        alertDialog2.setView(linearLayout);
        alertDialog2.setCancelable(false);
        alertDialog2.show();
    }


    private void move(){
        if(new Random().nextBoolean()){
            if (current_questionMCQ<mSQSList.size()-1){
                current_questionMCQ  ;
                moveToNextQuestion();
            }else if (current_questionTrueFalse<trueFalseQsList.size()-1) {
                current_questionTrueFalse  ;
                FragmentManager fm = getActivity().getSupportFragmentManager();
                Bundle mbundle = new Bundle();
                mbundle.putSerializable("trueFalseQsList", trueFalseQsList);
                mbundle.putSerializable("mSQSList", mSQSList);
                mbundle.putInt("current_questionMCQ", current_questionMCQ);
                mbundle.putInt("current_questionTrueFalse", current_questionTrueFalse);
                mbundle.putInt("score", score);
                mbundle.putBoolean("isFirstMCQ", isFirstMCQ);
                mbundle.putBoolean("isFirstTrueFalse", isFirstTrueFalse);
                ActivityTrueFalse homeFragment = new ActivityTrueFalse();
                homeFragment.setArguments(mbundle);
                fm.beginTransaction()
                        .replace(R.id.container, homeFragment)
                        .commit();
            }else{
                showDialogue();
            }
        }else{
            if (current_questionTrueFalse<trueFalseQsList.size()-1) {
                current_questionTrueFalse  ;
                FragmentManager fm = getActivity().getSupportFragmentManager();
                Bundle mbundle = new Bundle();
                mbundle.putSerializable("trueFalseQsList", trueFalseQsList);
                mbundle.putSerializable("mSQSList", mSQSList);
                mbundle.putInt("current_questionMCQ", current_questionMCQ);
                mbundle.putInt("current_questionTrueFalse", current_questionTrueFalse);
                mbundle.putInt("score", score);
                mbundle.putBoolean("isFirstMCQ", isFirstMCQ);
                mbundle.putBoolean("isFirstTrueFalse", isFirstTrueFalse);
                ActivityTrueFalse homeFragment = new ActivityTrueFalse();
                homeFragment.setArguments(mbundle);
                fm.beginTransaction()
                        .replace(R.id.container, homeFragment)
                        .commit();
            }else if (current_questionMCQ<mSQSList.size()-1){
                current_questionMCQ  ;
                moveToNextQuestion();
            }else{
                showDialogue();
            }

        }
    }
}