如何分别触发其他类和它的TextView和执行定时器另一个XML和类?它的、定时器、TextView、XML

2023-09-05 04:58:09 作者:演绎

我的工作在Android测验,并希望我的每一个问题回答页面上的定时器。我有菜单页面在我的测验和播放按钮开始游戏。我想这个定时器,当我点击播放按钮。对于此我要创建TextView的有关XML的重新present我的菜单页面。而在QuestionActivity类实现其重新present我的第一个问题页。我还张贴WelcomeActivity类,虽然它没有发挥在这个问题上的任何角色。

播放按钮布局

 <按钮
            机器人:文本=播放
            机器人:ID =@ + ID / playBtn
            机器人:layout_width =80dip
            机器人:layout_alignParentRight =真
            机器人:layout_height =WRAP_CONTENT
            机器人:paddingTop =5dip
            机器人:paddingBottom会=5dip
            机器人:文字颜色=#FFFFFF
            机器人:背景=@可绘制/ start_button/>
 

问题XML重新presenting TextView的定时器

 <的TextView
    机器人:ID =@ + ID / textView1
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:layout_above =@ + ID /问题
    机器人:layout_centerHorizo​​ntal =真
    机器人:背景=@可绘制/ timer_bttn
    机器人:的onClick =的onClick/>
 
无法执行语言识别

QuestionActivity在这里我实现定时code

 公共类QuestionActivity扩展活动实现OnClickListener {

    私人问题currentQ;
    私人游戏currentGame;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.question);
        / **
         *配置当前游戏并获得问题
         * /
        currentGame =((CYKApplication)getApplication())getCurrentGame()。
        currentQ = currentGame.getNextQuestion();
        按钮nextBtn1 =(按钮)findViewById(R.id.answer1);
        nextBtn1.setOnClickListener(本);
        按钮nextBtn2 =(按钮)findViewById(R.id.answer2);
        nextBtn2.setOnClickListener(本);
        按钮nextBtn3 =(按钮)findViewById(R.id.answer3);
        nextBtn3.setOnClickListener(本);
        按钮nextBtn4 =(按钮)findViewById(R.id.answer4);
        nextBtn4.setOnClickListener(本);
        / **
         *更新的问题和答案选项..
         * /
        setQuestions();

    }


    / **
     *方法来设置文本从目前游戏的问题和答案
     *当前问题
     * /
    私人无效setQuestions(){
        //设置与当前讨论的问题文本
        串质询= Utility.capitalise(currentQ.getQuestion());
        TextView的QTEXT =(TextView中)findViewById(R.id.question);
        qText.setText(问题);

        //设置的可用选项
        名单<字符串>答案= currentQ.getQuestionOptions();
        TextView的选项1 =(TextView中)findViewById(R.id.answer1);
        option1.setText(Utility.capitalise(answers.get(0)));

        TextView的选项2 =(TextView中)findViewById(R.id.answer2);
        option2.setText(Utility.capitalise(answers.get(1)));

        TextView的选项3 =(TextView中)findViewById(R.id.answer3);
        option3.setText(Utility.capitalise(answers.get(2)));

        TextView的选项4 =(TextView中)findViewById(R.id.answer4);
        option4.setText(Utility.capitalise(answers.get(3)));

        INT得分= currentGame.getScore();
        字符串SCR =将String.valueOf(分);
        TextView的score1 =(TextView中)findViewById(R.id.score);
        score1.setText(SCR);
    }


    @覆盖
    公共无效的onClick(查看为arg0){
        //Log.d("Questions,移动到下一个问题);
        如果收益率(checkAnswer(arg0中)!);

        / **
         *检查,如果游戏结束
         * /
        如果(currentGame.isGameOver()){
            !//Log.d("Questions,游戏结束让加起来的得分。);
            //Log.d("Questions,问题正确:+ currentGame.getRight());
        //Log.d("Questions,错误的问题:+ currentGame.getWrong());
        意图I =新的意图(这一点,EndgameActivity.class);
        startActivity(ⅰ);
        完();
        }
        其他 {
            意图I =新的意图(这一点,QuestionActivity.class);
        startActivity(ⅰ);
        完();
        }
    }

    @覆盖
    公共布尔的onkeydown(INT键code,KeyEvent的事件){
        开关(钥匙code)
        {
        案例KeyEvent.KEY code_BACK:
            返回true;
        }

        返回super.onKeyDown(键code,事件);
    }


    / **
     *检查复选框已被选中,并且如果它
     *已经然后检查其正确和更新gamescore
     * /
    私人布尔checkAnswer(视图v){

        按钮B =(按钮)V;
        。字符串答案= b.getText()的toString();

        //Log.d("Questions,有效复选框选择做 - 检查是否正确);
        如果(currentQ.getAnswer()。equalsIgnoreCase(答案))
        {
        //Log.d("Questions,正确答案)!;
        currentGame.incrementScore();
        }
        其他 {
        //Log.d("Questions,不正确的答案)!;
        currentGame.decrementScore();
        }

        返回true;
    }

    公共无效SetTimer的(){
        长finishTime = 5;
        CountDownTimer counterTimer =新CountDownTimer(finishTime * 1000,1000){
            公共无效onFinish(){
                // code时执行的时间完成
            }

            公共无效onTick(长millisUntilFinished){
                INT秒=(int)的(millisUntilFinished / 1000);
                INT分钟=秒/ 60;
                秒=秒%60;

                如果(秒-1,10){
                    txtTimer.setText(+分钟+:0+秒);
                } 其他 {
                    txtTimer.setText(+分钟+:+秒);
                }
            }
        };
        counterTimer.start();
    }

}
 

WelcomeActivity

 公共类WelcomeActivity扩展活动实现OnClickListener {
@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.welcome);

    ////////////////////////////////////////////////// ////////////////////
    ////////游戏菜单//////////////////////////////////////// /////////
    按钮playBtn =(按钮)findViewById(R.id.playBtn);
    playBtn.setOnClickListener(本);
    按钮settingsBtn =(按钮)findViewById(R.id.settingsBtn);
    settingsBtn.setOnClickListener(本);
    按钮rulesBtn =(按钮)findViewById(R.id.rulesBtn);
    rulesBtn.setOnClickListener(本);
    按钮exitBtn =(按钮)findViewById(R.id.exitBtn);
    exitBtn.setOnClickListener(本);
}


/ **
 *监听器为游戏菜单
 * /
@覆盖
公共无效的onClick(视图v){
    我的意图;

    开关(v.getId()){
    案例R.id.playBtn:
        //登录后,加载主页
        //Log.d("LOGIN,用户已经开始游戏);

        //获取问题集//
        名单<问题>题= getQuestionSetFromDb();

        //初始化游戏与检索问题集///
        游戏C =新的游戏();
        c.setQuestions(问题);
        c.setNumRounds(getNumQuestions());
        ((CYKApplication)getApplication())setCurrentGame(三);

        //开始游戏吧.. //
        I =新的意图(这一点,QuestionActivity.class);
        startActivityForResult(ⅰ,Constants.PLAYBUTTON);
        打破;

    案例R.id.rulesBtn:
        I =新的意图(这一点,RulesActivity.class);
        startActivityForResult(ⅰ,Constants.RULESBUTTON);
        打破;

    案例R.id.settingsBtn:
        I =新的意图(这一点,SettingsActivity.class);
        startActivityForResult(ⅰ,Constants.SETTINGSBUTTON);
        打破;

    案例R.id.exitBtn:
        完();
        打破;
    }

}
 

解决方案

正如刚才古普塔的Piyush ,你应该叫 SetTimer的()方法从 onResume QuestionActivity

从 Android开发者文档:

(onResume是)要求您的活动启动与用户交互。这是一个好地方,开始动画,开放异接入设备(如摄像机)等。

在你的code,你也应该让 counterTimer 您在 SetTimer的() A 类成员,不是一个局部变量;如果你不这样做就会超出范围,一旦 SetTimer的()调用完成,你的访问都将丢失。

所以,你需要将以下内容添加到 QuestionActivity

 公共类QuestionActivity扩展活动实现OnClickListener {

    //新:加counterTimer作为成员
    私人CountDownTimer counterTimer;

    //新:实施onResume
    @覆盖
    公共无效onResume(){
        SetTimer的();
        super.onResume();
    }

    //改变:如下的SetTimer应该改变
    公共无效SetTimer的(){
        长finishTime = 5;
        //注意:使用成员,而不是局部的
        counterTimer =新CountDownTimer(finishTime * 1000,1000){
            公共无效onFinish(){
                // code时执行的时间完成
            }

            公共无效onTick(长millisUntilFinished){
                INT秒=(int)的(millisUntilFinished / 1000);
                INT分钟=秒/ 60;
                秒=秒%60;

                如果(秒-1,10){
                    txtTimer.setText(+分钟+:0+秒);
                } 其他 {
                    txtTimer.setText(+分钟+:+秒);
                }
            }
        };
        counterTimer.start();
    }
}
 

这上面的例子中使用您的code因为它是现在,但我会建议你使用类成员来存储它创建于的onCreate 定时器(即。一切,这是目前在SetTimer的(),除了 counterTimer.start(); 打电话就用 counterTimer.start(); onResume 。也许添加 counterTimer.cancel()致电的onPause 这样,当活动失去焦点计时器结束。

I am working on android quiz and want timer on my each question-answer page. I have menu page in my quiz and play button to start game. And i want this timer is triggered when i click on play button. For this i have to create TextView in question XML that represent my menu page. And implementation in QuestionActivity class which represent my first question page. i am also posting WelcomeActivity class although its not play any role in this question.

Play Button Layout

<Button 
            android:text="Play" 
            android:id="@+id/playBtn"
            android:layout_width="80dip" 
            android:layout_alignParentRight="true"
            android:layout_height="wrap_content"
            android:paddingTop="5dip" 
            android:paddingBottom="5dip"
            android:textColor="#ffffff"
            android:background="@drawable/start_button" />

Question XML representing TextView for Timer

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/question"
    android:layout_centerHorizontal="true"
    android:background="@drawable/timer_bttn" 
    android:onClick="onClick"/>

QuestionActivity where i implemented timer code

public class QuestionActivity extends Activity implements OnClickListener{

    private Question currentQ;
    private GamePlay currentGame;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.question);
        /**
         * Configure current game and get question
         */
        currentGame = ((CYKApplication)getApplication()).getCurrentGame();
        currentQ = currentGame.getNextQuestion();
        Button nextBtn1 = (Button) findViewById(R.id.answer1);
        nextBtn1.setOnClickListener(this);
        Button nextBtn2 = (Button) findViewById(R.id.answer2);
        nextBtn2.setOnClickListener(this);
        Button nextBtn3 = (Button) findViewById(R.id.answer3);
        nextBtn3.setOnClickListener(this);
        Button nextBtn4 = (Button) findViewById(R.id.answer4);
        nextBtn4.setOnClickListener(this);
        /**
         * Update the question and answer options..
         */
        setQuestions();

    }


    /**
     * Method to set the text for the question and answers from the current games
     * current question
     */
    private void setQuestions() {
        //set the question text from current question
        String question = Utility.capitalise(currentQ.getQuestion());
        TextView qText = (TextView) findViewById(R.id.question);
        qText.setText(question);

        //set the available options
        List<String> answers = currentQ.getQuestionOptions();
        TextView option1 = (TextView) findViewById(R.id.answer1);
        option1.setText(Utility.capitalise(answers.get(0)));

        TextView option2 = (TextView) findViewById(R.id.answer2);
        option2.setText(Utility.capitalise(answers.get(1)));

        TextView option3 = (TextView) findViewById(R.id.answer3);
        option3.setText(Utility.capitalise(answers.get(2)));

        TextView option4 = (TextView) findViewById(R.id.answer4);
        option4.setText(Utility.capitalise(answers.get(3)));

        int score = currentGame.getScore();
        String scr = String.valueOf(score);
        TextView score1=(TextView) findViewById(R.id.score);
        score1.setText(scr);
    }


    @Override
    public void onClick(View arg0) {
        //Log.d("Questions", "Moving to next question");
        if(!checkAnswer(arg0)) return;  

        /**
         * check if end of game
         */
        if (currentGame.isGameOver()) {
            //Log.d("Questions", "End of game! lets add up the scores..");
            //Log.d("Questions", "Questions Correct: " + currentGame.getRight());
        //Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
        Intent i = new Intent(this, EndgameActivity.class);
        startActivity(i);
        finish();
        }
        else {
            Intent i = new Intent(this, QuestionActivity.class);
        startActivity(i);
        finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode)
        {
        case KeyEvent.KEYCODE_BACK :
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    /**
     * Check if a checkbox has been selected, and if it
     * has then check if its correct and update gamescore
     */
    private boolean checkAnswer(View v) {

        Button b=(Button) v;
        String answer = b.getText().toString();

        //Log.d("Questions", "Valid Checkbox selection made - check if correct");
        if (currentQ.getAnswer().equalsIgnoreCase(answer))
        {
        //Log.d("Questions", "Correct Answer!");
        currentGame.incrementScore();
        }
        else {
        //Log.d("Questions", "Incorrect Answer!");
        currentGame.decrementScore();
        }

        return true;
    }

    public void setTimer() {
        long finishTime = 5;
        CountDownTimer counterTimer = new CountDownTimer(finishTime * 1000, 1000) {
            public void onFinish() {
                //code to execute when time finished
            }

            public void onTick(long millisUntilFinished) {
                int seconds = (int) (millisUntilFinished / 1000);
                int minutes = seconds / 60;
                seconds = seconds % 60;

                if (seconds < 10) {
                    txtTimer.setText("" + minutes + ":0" + seconds);
                } else {
                    txtTimer.setText("" + minutes + ":" + seconds);
                }
            }
        };
        counterTimer.start();
    }

}

WelcomeActivity

public class WelcomeActivity extends Activity implements OnClickListener{
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.welcome);

    //////////////////////////////////////////////////////////////////////
    //////// GAME MENU  /////////////////////////////////////////////////
    Button playBtn = (Button) findViewById(R.id.playBtn);
    playBtn.setOnClickListener(this);
    Button settingsBtn = (Button) findViewById(R.id.settingsBtn);
    settingsBtn.setOnClickListener(this);
    Button rulesBtn = (Button) findViewById(R.id.rulesBtn);
    rulesBtn.setOnClickListener(this);
    Button exitBtn = (Button) findViewById(R.id.exitBtn);
    exitBtn.setOnClickListener(this);
}


/**
 * Listener for game menu
 */
@Override
public void onClick(View v) {
    Intent i;

    switch (v.getId()){
    case R.id.playBtn :
        //once logged in, load the main page
        //Log.d("LOGIN", "User has started the game");

        //Get Question set //
        List<Question> questions = getQuestionSetFromDb();

        //Initialise Game with retrieved question set ///
        GamePlay c = new GamePlay();
        c.setQuestions(questions);
        c.setNumRounds(getNumQuestions());
        ((CYKApplication)getApplication()).setCurrentGame(c);  

        //Start Game Now.. //
        i = new Intent(this, QuestionActivity.class);
        startActivityForResult(i, Constants.PLAYBUTTON);
        break;

    case R.id.rulesBtn :
        i = new Intent(this, RulesActivity.class);
        startActivityForResult(i, Constants.RULESBUTTON);
        break;

    case R.id.settingsBtn :
        i = new Intent(this, SettingsActivity.class);
        startActivityForResult(i, Constants.SETTINGSBUTTON);
        break;

    case R.id.exitBtn :
        finish();
        break;
    }

}

解决方案

As mentioned by Piyush Gupta, you should call the setTimer() method from onResume in your QuestionActivity.

From the Android Developer Documentation:

(onResume is) called for your activity to start interacting with the user. This is a good place to begin animations, open exclusive-access devices (such as the camera), etc.

In your code you should also make the counterTimer you use in setTimer() a class member, not a local variable; if you don't it will go out of scope once the setTimer() call completes and your access to it will be lost.

So you will need to add the following to QuestionActivity:

public class QuestionActivity extends Activity implements OnClickListener{

    // NEW: add counterTimer as a member
    private CountDownTimer counterTimer;

    // NEW: implement onResume
    @Override
    public void onResume() {
        setTimer();
        super.onResume();
    }

    // CHANGE: setTimer should be changed as follows
    public void setTimer() {
        long finishTime = 5;
        // NOTE: use the member, instead of a local
        counterTimer = new CountDownTimer(finishTime * 1000, 1000) {
            public void onFinish() {
                //code to execute when time finished
            }

            public void onTick(long millisUntilFinished) {
                int seconds = (int) (millisUntilFinished / 1000);
                int minutes = seconds / 60;
                seconds = seconds % 60;

                if (seconds < 10) {
                    txtTimer.setText("" + minutes + ":0" + seconds);
                } else {
                    txtTimer.setText("" + minutes + ":" + seconds);
                }
            }
        };
        counterTimer.start();
    }
}

This above example uses your code as it is now, but I would advise you to create the timer in onCreate using the class member to store it (ie. everything that is currently in setTimer(), except for the counterTimer.start(); call. Then just use counterTimer.start(); in onResume. And maybe add a counterTimer.cancel() call to onPause so that the timer ends when the activity loses focus.