当前位置: 首页 > 面试题库 >

如何从其他类及其TextView触发计时器,并分别在另一个xml和类中实现?

蒲勇
2023-03-14
问题内容

我正在从事android测验,并希望每个问题答案页面上都有计时器。我的测验中有菜单页面,然后单击播放按钮开始游戏。我希望当我单击“播放”按钮时触发此计时器。为此,我必须创建有问题的XML表示我的菜单页面的TextView。在QuestionActivity类中的实现,它代表了我的第一个问题页面。我也在发布WelcomeActivity类,尽管它在此问题中没有任何作用。

播放按钮布局

<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" />

代表TextView为Timer的问题XML

<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

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();
    }

}

欢迎活动

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;
    }

}

问题答案:

正Piyush Gupta所提到的,您应该在您的容器中调用该setTimer()方法。onResume``QuestionActivity

来自Android开发者文档:

(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.

在你的代码也应该使counterTimer你在使用setTimer()一个 类成员 ,而不是一个局部变量;
如果不这样做,则在setTimer()呼叫完成后它将超出范围,并且您对其的访问将丢失。

因此,您需要将以下内容添加到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();
    }
}

这上面的例子使用你的代码,因为它是现在,但我会建议你在创建定时器onCreate一切,这是目前在SetTimer的(),除了使用类成员来存储它(即counterTimer.start();调用。然后,只需用counterTimer.start();onResume。也许添加一个counterTimer.cancel()呼叫,onPause以便当活动失去焦点时计时器结束。



 类似资料:
  • 问题内容: 我非常感谢您为我的问题提供的一些帮助: 我有2个MySQL表,类别和帖子,它们的布局(简化)如下: 类别 : CATID-名称-parent_id 帖子 : PID-名称-类别 我想做的是获取每个类别的帖子总数,包括子类别中的所有帖子。 现在,我通过执行以下操作来获取每个(顶级)类别(而不是子类别)中的帖子总数: 再次的问题是,如何获得每个类别的总计,包括每个相关子类别的总计? 由于我

  • 我有服装产品。一种产品有多个类别,如“性别”(“男性”或“女性”)和“类型”(如“裤子”、“衬衫”等)。 我想列出所有类别和子类别的“类型”从产品中存在的“男子”类别。 "type"类别的ID: 1696 这段代码给了我1696下的所有类别,但我只想从也属于“男性”类别的产品中获得“类型”类别。 我明白了吗? 非常感谢你的帮助。

  • 我有两个表的项目和类别。类别表是自联接表。 项目表具有以下列ID、项目名称、类别ID Categories表包含以下列CATID、category\u name、parent\u ID 我需要选择在一个类别和这个主类别的子类别下列出但不起作用的项目。这里是mysql,它只返回sub。

  • 我需要让从类继承的类说A。 但我也想把它创建成通用的 我如何定义这样的类?

  • 我有一个很大的问题,我不知道我是否错过了一些明显的东西或什么,但我不能发现我的错误。我有类SPN、A和B。我重载了2次operator=。我想将A类型或B类型作为参数传递。 它不会抛出任何错误。但是如果我在类B或A中尝试make operator(),则使用参数SPN,如下所示: 它会抛出SPN未命名类型的错误。我甚至不能在A类或B类中创建类SPN对象。也许它不是如何客观编程工作,所以我想得到它,

  • 我想创建一个类,它的功能只是做一个碎片事务,但我有一个错误。我的课是下一个: 进程:net.elinformaticoenganchado.sergio.crossfights,PID:5116 java.lang.runtimeException:无法启动活动ComponentInfo{net.elinformaticoenganchado.sergio.crossfights/net.elin