如何在此Android测验中添加计时器?

如何解决如何在此Android测验中添加计时器?

我开发了一个Quiz程序,它以片段形式显示问题。

  • 对于是非题第一个片段
  • 对于MCQ第二片段
  • MainActivity(从主我将qs列表发送到mcq片段和另一个)

测验结束时,随机显示这2个片段。 但是我需要为每个片段添加一个计时器。我该如何实现?

我已经发布了MCQ Fragment的代码,其他的也一样。 (仅接口有所不同)我想知道我到底需要在哪里放置计时器。

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 & 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",Quiz_Main.class));
                    }
                });
        total_questions.setPadding(100,30,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",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,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",homeFragment)
                        .commit();
            }else if (current_questionMCQ<mSQSList.size()-1){
                current_questionMCQ++;
                moveToNextQuestion();
            }else{
                showDialogue();
            }

        }
    }
}


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-